简体   繁体   English

从列表python添加类似的字母数字元素

[英]Add similar alphanumeric elements from list python

I have two list A = ['1a', '3c'] and B = ['2a', '1b'] . 我有两个列表A = ['1a', '3c']B = ['2a', '1b'] I want to add the strings which ends with same character and update the contents of A like shown below: 我想添加以相同字符结尾的字符串,并更新A的内容,如下所示:

Final result to be: A = ['3a', '3c'] . 最终结果为: A = ['3a', '3c'] Below is my code: 下面是我的代码:

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] 

You can use regex to split the int from the chars, and then sum if they are equals, with list comp it would be (considering the len of two lists are equals): 您可以使用正则表达式从char中拆分int,然后将它们相等,然后用list comp求和(考虑两个列表的len等于):

import re 汇入

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']

Try something like this: 尝试这样的事情:

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