繁体   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