3

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]]
avasal
  • 14,350
  • 4
  • 31
  • 47
user1220022
  • 11,167
  • 19
  • 41
  • 57
  • 3
    possible duplicate of [python list of lists transpose without zip(*m) thing](http://stackoverflow.com/questions/6473679/python-list-of-lists-transpose-without-zipm-thing) – senderle Apr 12 '12 at 02:29
  • 3
    possible duplicate of [A Transpose/Unzip Function in Python](http://stackoverflow.com/questions/19339/a-transpose-unzip-function-in-python) – agf Apr 12 '12 at 02:33
  • Is this really an array as specified by NumPy? Or an object of type `array` as created by the `array` module? Because what you've described looks instead like a `list`. – Karl Knechtel Apr 12 '12 at 03:20

2 Answers2

6

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]]
ely
  • 74,674
  • 34
  • 147
  • 228
  • 1
    There is _no need_ for external libraries for something this simple. – agf Apr 12 '12 at 02:33
  • 1
    That doesn't mean they aren't a good thing to use. There can be many good things to use, and knowing many of them is a good thing. – ely Apr 12 '12 at 02:34
  • 1
    The OP mentioned array, so it makes sense to bring up numpy. – Akavall Apr 12 '12 at 02:42
4
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)]
avasal
  • 14,350
  • 4
  • 31
  • 47