Is there a function to convert matrices in python? example [1,2],[4,5],[7,8] => ans : [1,4,7],[2,5,8]
2 Answers
You can use zip function, like this
l = [[1,2,3],[4,5,6],[7,8,9]]
print zip(*l)
Output
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
5 Comments
Yanshuai Cao
what a clever use of zip and argument expansion
thefourtheye
@caoy People used to call this as argument unpacking :)
Yanshuai Cao
lol, thanks, i knew i shouldn't just invent names :P
pukluk
@ thefourtheye if rows not equal columns. example [[1,2,3,4],[5,6,7,8],[9,0,11,12]] output [[1,5,9],[2,6,0],[3,7,11],[4,8,12]]
thefourtheye
@pukluk It will still work. Please try that yourself :)
Depending on your program, you may want to use numpy:
In [1]: m = np.array([[1,2,3],[4,5,6],[7,8,9]])
In [2]: m
Out[2]:
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
In [3]: m.T
Out[3]:
array([[1, 4, 7],
[2, 5, 8],
[3, 6, 9]])