I have a Python assignment where I have to transpose a multi-dimensional matrix (3×3, 4×4,5×5…) without using any for-loops but only using list comprehension.
As an example for a 2×2 matrix, we have:
a2 = [[1, 2], [3, 4]]
n = len(a2)
print [[row[i] for row in a2] for i in range(n)]
But I am not sure I really understand how it works or how to adapt it for a 3×3, 4×4, 5×5… matrix
For instance, with
a3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
I don’t necessarily want you to give me the answer (still have to figure out by myself), but any hint would be very helpful!
Thanks in advance!
There is a built-in for this – the
zip()function.Note that the call to
list()is to show the result, in 3.x, this produces an iterable, not a list (which is lazy, giving memory benefits). In 2.x, it returns a list anyway.If you want to transpose the internal parts as well in an example with more nested lists, then it’s relatively simple to use a list comprehension to run
zip()on the sublists.Example in 2.x for ease of reading: