3

Need help that I got lost in zipping two lists of lists (matrix).

The matrices that exactly the same format, that I would like them to be zipped in tuple pairs for each element in the same position.

For example,

m1 = [['A', 'B', 'C'],
      ['D', 'E'],
      ['F', 'G']]

m2 = [['s1', 's2', 's3'],
      ['s4', 's5'],
      ['s1', 's3']]

What I expect to get is, with the same format:

z = [[('A', 's1'), ('B', 's2'), ('C', 's3')],
     [('D', 's4'), ('E', 's5')],
     [('F', 's1'), ('G', 's3')]]

I can write a function to do this but I am looking for an elegant way of doing this in Python.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

1 Answers1

6

zip() and zip() again:

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

The zip() function pairs up each element of the input sequences; m1[0] with m2[0], m1[1] with m2[1], etc., and then for each of those pairs you then pair the elements again (m1[0][0] with m2[0][0], m1[0][1] with m2[0][1], etc.).

If this is Python 3, you'll have to wrap one of those in a list() call:

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

Demo:

>>> m1 = [['A', 'B', 'C'],
...       ['D', 'E'],
...       ['F', 'G']]
>>> m2 = [['s1', 's2', 's3'],
...       ['s4', 's5'],
...       ['s1', 's3']]
>>> [zip(*paired) for paired in zip(m1, m2)]
[[('A', 's1'), ('B', 's2'), ('C', 's3')], [('D', 's4'), ('E', 's5')], [('F', 's1'), ('G', 's3')]]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343