I have a list
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
I want to convert it to
a = [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
How can I do this?
Try using zip
function, and use *a
to unpack:
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
print zip(*a)
>>> [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]
If you want lists instead of tuples:
print map(list, zip(*a))
>>> [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
use zip
.
print zip(*a)
If you really want a list of lists, instead of a list of tuple:
[list(x) for x in zip(*a)]
will do the trick (and, as a bonus, this works the same on python2.x and python3.x)