簡體   English   中英

從列表python添加類似的字母數字元素

[英]Add similar alphanumeric elements from list python

我有兩個列表A = ['1a', '3c']B = ['2a', '1b'] 我想添加以相同字符結尾的字符串,並更新A的內容,如下所示:

最終結果為: A = ['3a', '3c'] 下面是我的代碼:

for x, y in enumerate(A):
        # gets the indices of B which has same end character
        l = [B.index(i) for i in B if y[1] in i] 

您可以使用正則表達式從char中拆分int,然后將它們相等,然后用list comp求和(考慮兩個列表的len等於):

匯入

A = ['1a', '3c', "2b"]
B = ['2a', '1b', "4c"]

def splitNum(x):
  return list(filter(None, re.split(r'(\d+)', x)))

A = [str(int(splitNum(x)[0]) + int(splitNum(y)[0])) + (splitNum(x)[1]) for x in A for y in B if splitNum(x)[1] == splitNum(y)[1]]

print(A)

 => ['3a', '7c', '3b']

嘗試這樣的事情:

A = ['1a', '3c'] 
B = ['2a', '1b']
for i, (x, y) in enumerate(zip(A, B)):
  if x[-1] == y[-1]:
    A[i] = str(int(x[0])+int(y[0])) + x[-1]
print A 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM