简体   繁体   中英

How to merge two list of strings with multiple character replacements

I have two lists of strings.

A = ['HKO', 'HKO', 'HKO'] 
B = ['12M', 'M4M', 'MKO']

I want to merge them such that the result is:

C = ['HKM', 'MKM', 'MKO']

That is, if there is an 'M' in list B , I want to keep it, else I want to replace it with the value in that index of A.

What is the best way to do this? The problem I keep encountering is B's 'M4M' such that I'm unable to replace both the 'H' and the 'O' . For example I'll get:

['HKM', 'MKO', 'HKM'] 

Thanks. (The code I have so far is below!)

replace_list = [(0, 2), (1, 0), (1, 2), (2, 0)]

list = []
for i in range(len(mix_list)):
    for j in range(len(letters)):
        if j != replace_list[i][1]:
            list.append(letters[i][j])
        else:
            list.append('M')
    list_join = ("".join(list))

    print list
print "join", list_join

where I get: join HKMMKOHKM

You can use the function map() with the helper function func() :

A = ['HKO', 'HKO', 'HKO']
B = ['12M', 'M4M', 'MKO']

def func(a, b):
    if 'M' in b:
        m = map(lambda x, y:
            y if y == 'M' else x, a, b)
        return ''.join(m)
    else:
        return a

list(map(func, A, B))
# ['HKM', 'MKM', 'MKO']

Playing around with zip s and map s

f = lambda s: ''.join([a if b !='M' else b for a, b in s])
list(map(f, (map(lambda k: zip(*k), zip(A,B)))))

Outputs

['HKM', 'MKM', 'MKO']

You can use zip and str.join :

A = ['HKO', 'HKO', 'HKO'] 
B = ['12M', 'M4M', 'MKO']
result = [''.join(d if d == 'M' else c for c, d in zip(a, b)) for a, b in zip(A, B)]

Output:

['HKM', 'MKM', 'MKO']

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