>>> grid = [(1, 2, 3), (4, 5, 6)]
>>> list(zip(*grid))
[(1, 4), (2, 5), (3, 6)]
>>> grid = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
>>> list(zip(*grid))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
numpy makes this a breeze - numpy.transpose(matrix) - but you can also use the zip() built-in function, leveraging the fact that it iterates over several iterables in parallel, producing new tuples with an item from each one.
So here feeding zip the tuples (1, 2, 3) and (4, 5, 6) it matches ("zips up"):
- 1 and 4 -> (1, 4)
- 2 and 5 -> (2, 5)
- 3 and 6 -> (3, 6)
= effectively transposing the grid.
bbelderbos
python