我有两个列表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]
答案 0 :(得分:1)
你可以使用正则表达式从字符中拆分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']
答案 1 :(得分:1)
尝试这样的事情:
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