Friday, January 14, 2011

Transpose Matrix

>>> mat = [
...        [1, 2, 3],
...        [4, 5, 6],
...        [7, 8, 9],
...       ]
>>> print [[row[i] for row in mat] for i in [0, 1, 2]]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]



matt = zip(*mat)

>>> mat = [[1, 2, 3],[4, 5, 6],[7, 8, 9]]
>>> mat
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> mat[0]
[1, 2, 3]
>>> mat[0][1]
2
>>> matt = zip(*mat)
>>> matt
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> type(matt)
<type 'list'>
>>> matt[0]
(1, 4, 7)
>>> [list(i) in matt[i]]
Traceback (most recent call last):
  File "<pyshell#82>", line 1, in <module>
    [list(i) in matt[i]]
NameError: name 'i' is not defined
>>> [list(i) for i in matt[i]]
Traceback (most recent call last):
  File "<pyshell#83>", line 1, in <module>
    [list(i) for i in matt[i]]
NameError: name 'i' is not defined
>>> [list(i) for i in matt]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
>>> matt
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> type(matt)
<type 'list'>
>>> matt[0][1]
4
>>>

No comments:

Post a Comment