Reputation: 569
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?
Upvotes: 0
Views: 322
Reputation:
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')]
>>>
Upvotes: 1
Reputation: 413
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))
Upvotes: 0
Reputation: 122024
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))
Upvotes: 1
Reputation: 22561
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')]
Upvotes: 2