Python column split

I have a python array in the format:

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

Is there a way to split it into columns to give:

[[1,4,7],[2,5,8],[3,6,9]]
+3
source share
2 answers

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]]
+6
source
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 a 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)]
+4
source

All Articles