A short way to turn rows into columns. Not necessarily the fastest, mind you. The list comprehension is your friend.
1 2 3 4 5 6 7 | arr = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
# The subject should be regular, with all rows the same length
print [[r[col] for r in arr] for col in range(len(arr[0]))]
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
|
Sometimes data just comes at you the wrong way. For instance, if you use Microsoft's ADO database interface, due to array element ordering differences betwen Python and Microsoft's implementation language, the GetRows() method actually appears to return database columns in Python, despite its name. This solution was chosen to demonstrate nested list comprehensions. Notice that the inner comprehension varies what is selected from (the row) rather than the selector (the column), which is varied in the outer comprehension. This achieves the required transposition.
Shorter and Faster.
Not the same! While the original proposal returns a list of lists, zip(*arr) returns a list of tuples, and as a consequence the elements of the array cannot be modifed anymore.
OK then... map(list, zip(*arr))