简体   繁体   中英

Add similar alphanumeric elements from list python

I have two list A = ['1a', '3c'] and B = ['2a', '1b'] . I want to add the strings which ends with same character and update the contents of A like shown below:

Final result to be: 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):

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM