Fast matrix transposition in Python

Is there any quick way to transpose a rectangular 2D matrix in Python (without involving any library import)?

Say if I have an array

X=[ [1,2,3], [4,5,6] ] 

I need an array of Y, which should be a transposed version of X, so

 Y=[ [1,4], [2,5], [3,6] ] 
+4
source share
3 answers

Simple: Y = zip (* X)

 >>> X=[[1,2,3], [4,5,6]] >>> Y=zip(*X) >>> Y [(1, 4), (2, 5), (3, 6)] 

EDIT: answer the questions in the comments about what zip (* X) means, here is an example from the 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 - [[1,2,3], [4,5,6]] , zip(*X) - zip([1,2,3], [4,5,6])

+18
source
 >>> X = [1,2,3], [4,5,6]] >>> zip(*X) [(1,4), (2,5), (3,6)] >>> [list(tup) for tup in zip(*X)] [[1,4], [2,5], [3,6]] 

If the inner pairs must be lists, go with the second.

+6
source

If you work with matrices, you will almost certainly use numpy . This will make numerical operations easier and more efficient than pure Python code.

 >>> x = [[1,2,3], [4,5,6]] >>> x = numpy.array(x) >>> x array([[1, 2, 3], [4, 5, 6]]) >>> xT array([[1, 4], [2, 5], [3, 6]]) 

โ€œnot linking any import of the libraryโ€ is a stupid, unproductive requirement.

+5
source

Source: https://habr.com/ru/post/1311092/


All Articles