Concatenate items in two nested lists to pairs in

2019-09-06 17:20发布

I have two nested lists:

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

and I'd like the following result [(a,e), (b,f), (c,g), (d,h)]

I've tried zip(a,b), how do I zip nested lists into a list with tupled pairs?

4条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-06 17:56

You need to flatten your lists, and could use reduce:

from functools import reduce # in Python 3.x
from operator import add
zip(reduce(add, ls1), reduce(add, ls2))
查看更多
干净又极端
3楼-- · 2019-09-06 18:07

You can also use itertools.chain.from_iterable and 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')]
查看更多
看我几分像从前
4楼-- · 2019-09-06 18:11

An idiomatic method is to use the star notation and itertools.chain to flatten the lists before zipping them. The star notation unpacks an iterable into arguments to a function, while the itertools.chain function chains the iterables in its arguments together into a single iterable.



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

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

查看更多
祖国的老花朵
5楼-- · 2019-09-06 18:18

You can use zip twice inside a list comprehension:

>>> 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')]
>>>
查看更多
登录 后发表回答