简体   繁体   English

如何明智地连接多个列表元素

[英]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. 看起来像str.__add__不接受两个以上的列表对象。

Any workaround ? 任何解决方法?

Edit: Based on Jim Fasarakis-Hilliard comment. 编辑:基于Jim Fasarakis-Hilliard的评论。

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

Expected output: 预期产量:

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

Thanks 谢谢

Seems like you need zip 好像你需要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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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