让我们来:
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
我想要的结果是
r = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
而不是
r = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
让我们来:
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
我想要的结果是
r = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
而不是
r = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
当前回答
import numpy as np
r = list(map(list, np.transpose(l)))
其他回答
只是为了好玩:如果你想把它们都做成字典的话。
In [1]: l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
...: fruits = ["Apple", "Pear", "Peach",]
...: [dict(zip(fruits, j)) for j in [list(i) for i in zip(*l)]]
Out[1]:
[{'Apple': 1, 'Pear': 4, 'Peach': 7},
{'Apple': 2, 'Pear': 5, 'Peach': 8},
{'Apple': 3, 'Pear': 6, 'Peach': 9}]
只是为了好玩,有效的矩形假设m[0]存在
>>> m = [[1,2,3],[4,5,6],[7,8,9]]
>>> [[row[i] for row in m] for i in range(len(m[0]))]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
More_itertools.unzip()很容易阅读,它也可以用于生成器。
import more_itertools
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
r = more_itertools.unzip(l) # a tuple of generators.
r = list(map(list, r)) # a list of lists
或者同样的
import more_itertools
l = more_itertools.chunked(range(1,10), 3)
r = more_itertools.unzip(l) # a tuple of generators.
r = list(map(list, r)) # a list of lists
下面是一个不一定是平方的列表的转置的解决方案:
maxCol = len(l[0])
for row in l:
rowLength = len(row)
if rowLength > maxCol:
maxCol = rowLength
lTrans = []
for colIndex in range(maxCol):
lTrans.append([])
for row in l:
if colIndex < len(row):
lTrans[colIndex].append(row[colIndex])
方阵的另一种方法。不使用numpy和itertools,使用(有效的)就地元素交换。
def transpose(m):
for i in range(1, len(m)):
for j in range(i):
m[i][j], m[j][i] = m[j][i], m[i][j]