user1220022
user1220022

Reputation: 12105

python column split

I have a python array in the format:

[[1,2,3],[4,5,6],[7,8,9]]

Is there a way for me to break it up into columns to give:

[[1,4,7],[2,5,8],[3,6,9]]

Upvotes: 3

Views: 1682

Answers (2)

avasal
avasal

Reputation: 14872

In [85]: [list(x) for x in zip(*[[1,2,3],[4,5,6],[7,8,9]])]
Out[85]: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

If you want list of tuples you can use:

In [86]: zip(*[[1,2,3],[4,5,6],[7,8,9]])
Out[86]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

Upvotes: 4

ely
ely

Reputation: 77514

I think NumPy is good for this:

>>> import numpy as np
>>> my_list = [[1,2,3],[4,5,6],[7,8,9]]
>>> x = np.array(my_list)
>>> np.transpose(x).tolist()
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]

Upvotes: 6

Related Questions