定义:
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']]
有没有更好的方法来实现它?
答案 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']]