2013-07-01 529 views
0

的定义:最Python的矩阵转置

def transpose(matrix): 
    return [[i[j] for i in matrix] for j in range(0, len(matrix[0]))] 

和几个例子:

>>> transpose([[2]]) 
[[2]] 
>>> transpose([[2, 1]]) 
[[2], [1]] 
>>> transpose([[2, 1], [3, 4]]) 
[[2, 3], [1, 4]] 
>>> transpose([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]) 
[['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'i']] 

有没有实现任何更好的办法?

回答

2

使用zip*

>>> lis = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] 
>>> zip(*lis) 
[('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')] 

如果你想列出的清单:

>>> [list(x) for x in zip(*lis)] 
[['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'i']] 

使用itertools.izip内存有效的解决方案:

>>> from itertools import izip 
>>> [list(x) for x in izip(*lis)] 
[['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f', 'i']] 
3

如果转换为numpy数组,你可以使用T:

>>> import numpy as np 
>>> a = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']] 
>>> a = np.asarray(a) 
>>> a 
array([['a', 'b', 'c'], 
     ['d', 'e', 'f'], 
     ['g', 'h', 'i']], 
     dtype='|S1') 
>>> a.T 
array([['a', 'd', 'g'], 
     ['b', 'e', 'h'], 
     ['c', 'f', 'i']], 
     dtype='|S1')