python - Zipping two list of lists -


need got lost in zipping 2 lists of lists (matrix).

the matrices same format, them zipped in tuple pairs each element in same position.

for example,

m1 = [['a', 'b', 'c'],       ['d', 'e'],       ['f', 'g']]  m2 = [['s1', 's2', 's3'],       ['s4', 's5'],       ['s1', 's3']] 

what expect is, same format:

z = [[('a', 's1'), ('b', 's2'), ('c', 's3')],      [('d', 's4'), ('e', 's5')],      [('f', 's1'), ('g', 's3')]] 

i can write function looking elegant way of doing in python.

zip() , zip() again:

[zip(*paired) paired in zip(m1, m2)] 

the zip() function pairs each element of input sequences; m1[0] m2[0], m1[1] m2[1], etc., , each of pairs pair elements again (m1[0][0] m2[0][0], m1[0][1] m2[0][1], etc.).

if python 3, you'll have wrap 1 of in list() call:

[list(zip(*paired)) paired in zip(m1, m2)] 

demo:

>>> m1 = [['a', 'b', 'c'], ...       ['d', 'e'], ...       ['f', 'g']] >>> m2 = [['s1', 's2', 's3'], ...       ['s4', 's5'], ...       ['s1', 's3']] >>> [zip(*paired) paired in zip(m1, m2)] [[('a', 's1'), ('b', 's2'), ('c', 's3')], [('d', 's4'), ('e', 's5')], [('f', 's1'), ('g', 's3')]] 

Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -