Concatenate Items In Two Nested Lists To Pairs In Tuples
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
Solution 1:
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')]
Solution 2:
You need to flatten your lists, and could use reduce
:
from functools import reduce # in Python 3.xfromoperator import addzip(reduce(add, ls1), reduce(add, ls2))
Solution 3:
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))
Post a Comment for "Concatenate Items In Two Nested Lists To Pairs In Tuples"