Reputation: 6367
I have two 2d lists, e.g:
a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]
Then how can I get one 2d list of tuples: [[(1,5), (2,6)], [(3,7), (4,8)]]?
Upvotes: 0
Views: 170
Reputation: 13079
I see that you have answered your own question, as follows:
[[(i1,j1) for i1, j1 in zip(i, j)] for i, j in zip(a, b)]
However, a simplified form exists, along similar lines but working directly with the tuples instead of unpacking them into multiple variables -- also the first list comprehension can be replaced by just calling list
on the output of zip
:
[list(zip(*t)) for t in zip(a,b)]
or alternatively:
vars = (a, b)
[list(zip(*t)) for t in zip(*vars)]
As well as being slightly simpler, this has the advantage that it is easier to generalise to more variables, for example if you had:
a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]
c = [[9, 10], [11, 12]]
Then you could do:
vars = (a, b, c)
[list(zip(*t)) for t in zip(*vars)]
to give you:
[[(1, 5, 9), (2, 6, 10)], [(3, 7, 11), (4, 8, 12)]]
Upvotes: 2
Reputation: 6367
I used this code:
data = [[(i1,j1) for i1, j1 in zip(i, j)] for i, j in zip(a, b)]
Upvotes: 1