Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast matrix transposition in Python

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] ] 
like image 991
psihodelia Avatar asked Nov 28 '22 08:11

psihodelia


1 Answers

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])

like image 75
unbeli Avatar answered Dec 24 '22 01:12

unbeli