0

定义:

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']]

有没有更好的方法来实现它?

4

2 回答 2

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')
于 2013-07-02T02:23:55.500 回答
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']]
于 2013-07-01T21:24:52.580 回答