Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python matrix transpose and zip

Tags:

python

How to get the transpose of this matrix..Any easier ,algorithmic way to do this...

1st question:

 Input  a=[[1,2,3],[4,5,6],[7,8,9]]
 Expected output a=[[1, 4, 7], [2, 5, 8], [3, 6, 9]] 

2nd Question:

Zip gives me the following output said below,how can i zip when i dont know how many elements are there in the array,in this case i know 3 elements a[0],a[1],a[2] but how can i zip a[n] elements

 >>> zip(a[0],a[1],a[2])
 [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
like image 396
Rajeev Avatar asked Apr 16 '12 07:04

Rajeev


People also ask

How do you zip a matrix in python?

The zip() function in Python programming is a built-in standard function that takes multiple iterables or containers as parameters. An iterable in Python is an object that you can iterate over or step through like a collection. You can use the zip() function to map the same indexes of more than one iterable.

How do you create a matrix and transpose in Python?

For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix. The first row can be selected as X[0] . And, the element in the first-row first column can be selected as X[0][0] . Transpose of a matrix is the interchanging of rows and columns.

How do you switch columns and rows in a matrix in python?

Use the T attribute or the transpose() method to swap (= transpose) the rows and columns of DataFrame. Neither method changes an original object but returns the new object with the rows and columns swapped (= transposed object).


1 Answers

Use zip(*a):

>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

How it works: zip(*a) is equal to zip(a[0], a[1], a[2]).

like image 152
Udi Avatar answered Sep 22 '22 18:09

Udi