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?
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?
You need to flatten your lists, and could use
reduce
:You can also use itertools.chain.from_iterable and
zip
: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 theitertools.chain
function chains the iterables in its arguments together into a single iterable.You can use
zip
twice inside a list comprehension: