Is there any fast method to make a transposition of a rectangular 2D matrix in Python (non-involving any library import).?
Say, if I have an array
X=[ [1,2,3],
[4,5,6] ]
I need an array Y which should be a transposed version of X, so
Y=[ [1,4],
[2,5],
[3,6] ]
Simple: Y=zip(*X)
>>> X=[[1,2,3], [4,5,6]]
>>> Y=zip(*X)
>>> Y
[(1, 4), (2, 5), (3, 6)]
EDIT: to answer questions in the comments about what does zip(*X) mean, here is an example from python manual:
>>> range(3, 6) # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
So, when X
is [[1,2,3], [4,5,6]]
, zip(*X)
is zip([1,2,3], [4,5,6])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With