我有两个嵌套列表:
ls1 = [["a","b"], ["c","d"]]
ls2 = [["e","f"], ["g","h"]]
我希望得到以下结果[(a,e),(b,f),(c,g),(d,h)]
我已经尝试过zip(a,b),如何将嵌套列表压缩成带有元组对的列表?
答案 0 :(得分:2)
您还可以使用itertools.chain.from_iterable和zip
:
>>> 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')]
答案 1 :(得分:1)
您可以在list comprehension内使用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')]
>>>
答案 2 :(得分:1)
您需要展开列表,并可以使用reduce
:
from functools import reduce # in Python 3.x
from operator import add
zip(reduce(add, ls1), reduce(add, ls2))
答案 3 :(得分:0)
惯用方法是使用星号表示法和itertools.chain
在压缩列表之前展平列表。星号表示法将一个iterable解包为函数的参数,而itertools.chain
函数将其参数中的iterables链接在一起成为一个可迭代的。
ls1 = [["a","b"], ["c","d"]]
ls2 = [["e","f"], ["g","h"]]
import itertools as it
zip(it.chain(*ls1), it.chain(*ls2))