Pinning two lists of lists
Need help which I lost by running two lists of lists (matrix).
Matrices that are exactly the same format that I would like them to be zipped in pairs of tuples for each element at 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 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'm looking for an elegant way to do it in Python.
source to share
zip()
and zip()
again:
[zip(*paired) for paired in zip(m1, m2)]
The function connects each element of the input sequences; s , s , etc., and then for each of those pairs, you then reconnect the elements ( with , with , etc.). zip()
m1[0]
m2[0]
m1[1]
m2[1]
m1[0][0]
m2[0][0]
m1[0][1]
m2[0][1]
If it's Python 3, you'll have to wrap one of these in a call list()
:
[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')]]
source to share