简体   繁体   中英

How to concatenate multiple lists element wise

Inputs:

l1 = ['a', '', '', '']
l2 = ['', 'b', '', '']
l3 = ['', '', 'c', '']
l4 = ['', '', '', 'd']

Expected output:

['a', 'b', 'c', 'd']

I tried

list(map(str.__add__, l1, l2, l3, l4))

looks like str.__add__ doesn't accept more than two list objects.

Any workaround ?

Edit: Based on Jim Fasarakis-Hilliard comment.

l1 = ['a', '1', '', '']
l2 = ['', 'b', '2', '']
l3 = ['', '', 'c', '']
l4 = ['', '', '', 'd']

Expected output:

['a', '1b', '2c', 'd']

Thanks

Seems like you need zip

[''.join(x) for x in zip(l1, l2, l3, l4)]
# ['a', 'b', 'c', 'd']

For the updated input:

[''.join(x) for x in zip(l1, l2, l3, l4)]
# ['a', '1b', '2c', 'd']

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