python matrix transpose and zip

Question:

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)]
Asked By: Rajeev

||

Answers:

You can use numpy.transpose

numpy.transpose

>>> import numpy
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> numpy.transpose(a)
array([[1, 4, 7],
       [2, 5, 8],
       [3, 6, 9]])

question answers:

>>> import numpy as np
>>> first_answer = np.transpose(a)
>>> second_answer = [list(i) for i in zip(*a)]

thanks to afg for helping out

Answered By: luke14free

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

Answered By: Udi

Solution is to use tuple() function.

Here is an example how to do that in your case :

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

print(output)
Answered By: Marijan Milovec

You can use list(zip(*a)).

By using *a, your list of lists can have any number of entries.

Answered By: Jeet Bhavsar

Try this replacing appropriate variable

import numpy as np

data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))

data_transpose = np.transpose(data) # replace with your code
print(data_transpose)
Answered By: Abideen Muhammed
  1. Without zip

     def transpose(A):
        res = []
    
        for col in range(len(A[0])):
            tmp = []
            for row in range(len(A)):
                tmp.append(A[row][col])
    
            res.append(tmp)
    
        return res
    
  2. Using zip

    def transpose(A):
        return map(list, zip(*A))
    
Answered By: ashutosh
data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))

data_transpose = tuple(zip(*data))
print(data_transpose)
Answered By: Chisekana
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.