最pythonic矩阵转置

时间:2013-07-01 21:21:50

标签: python list matrix

定义:

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 个答案:

答案 0 :(得分: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')

答案 1 :(得分: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']]