简体   繁体   中英

match and replace string items in list with string items from another list

I have three lists - base, match, and replac ; match and replac are same length

base = ['abc', 'def', 'hjk']

match = ['abc', 'hjk']

replac = ['abcde', 'hjklm']

I would like to modify the base list by matching string items in match and replace these with the same index item from replac .

Expected output: base = ['abcde', 'def', 'hjklm']

Here is how I'd do it:

mapp = dict(zip(match,replac))
res = [mapp[e] if e in mapp else e for e in base]

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