Reputation: 15
I have a list
a = [[1,2],[3,4],[5,6],[7,8],[9,10]]
Result
New_a = [[1,3,5,7,9],[2,4,6,8,10]]
Any smart way or python built-in function can solve the problem?
Upvotes: 0
Views: 164
Reputation: 86168
import numpy as np
a = np.array([[1,2],[3,4],[5,6],[7,8],[9,10]])
Result:
>>> a
array([[ 1, 2],
[ 3, 4],
[ 5, 6],
[ 7, 8],
[ 9, 10]])
>>> a.T
array([[ 1, 3, 5, 7, 9],
[ 2, 4, 6, 8, 10]])
Upvotes: 1
Reputation: 25954
list(zip(*a))
Out[6]: [(1, 3, 5, 7, 9), (2, 4, 6, 8, 10)]
Explanation: zip
takes two or more iterables and stitches them together where "the i-th element comes from the i-th iterable argument." The star operator unpacks a
so that you zip the elements together, not the sublists.
Upvotes: 7
Reputation: 95242
You can use zip
in conjunction with the flattening operator *
:
[list(t) for t in zip(*a)]
You could also just use zip(*a)
by itself if (1) you're using Python 2 and (2) you don't mind getting a list of tuples instead of a list of lists.
Upvotes: 2