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)]
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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]).
Method 2
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
Method 3
You can use 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]])
Method 4
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)
Method 5
You can use list(zip(*a)).
By using *a, your list of lists can have any number of entries.
Method 6
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)
Method 7
-
Without zip
def transpose(A): res = [] for col in range(len(A[0])): tmp = [] for row in range(len(A)): tmp.append(A<div class="su-row"></div>[col]) res.append(tmp) return res -
Using zip
def transpose(A): return map(list, zip(*A))
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0