繁体   English   中英

将两个嵌套列表中的项目连接成元组对

[英]Concatenate items in two nested lists to pairs in tuples

我有两个嵌套列表:

ls1 = [["a","b"], ["c","d"]]
ls2 = [["e","f"], ["g","h"]]

我想要以下结果[(a,e),(b,f),(c,g),(d,h)]

我已经尝试过zip(a,b),如何将嵌套列表压缩到具有元组对的列表中?

您还可以使用itertools.chain.from_iterablezip

>>> ls1 = [["a","b"], ["c","d"]]
>>> ls2 = [["e","f"], ["g","h"]]
>>> 
>>> zip(itertools.chain.from_iterable(ls1), itertools.chain.from_iterable(ls2))
[('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', 'h')]

您可以在列表理解内两次使用zip

>>> ls1 = [["a","b"], ["c","d"]]
>>> ls2 = [["e","f"], ["g","h"]]
>>> [y for x in zip(ls1, ls2) for y in zip(*x)]
[('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', 'h')]
>>>

您需要拼合列表,并可以使用reduce

from functools import reduce # in Python 3.x
from operator import add
zip(reduce(add, ls1), reduce(add, ls2))

惯用的方法是使用星号和itertools.chain压缩列表,然后再压缩它们。 星号表示法将一个可迭代对象分解为函数的参数,而itertools.chain函数将其参数中的可迭代对象链接到一个可迭代对象中。



    ls1 = [["a","b"], ["c","d"]]
    ls2 = [["e","f"], ["g","h"]]

    import itertools as it
    zip(it.chain(*ls1), it.chain(*ls2))

暂无
暂无

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

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