让我们来:
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 functions from library
from numpy import size, array
#Transpose a 2D list
def transpose_list_2d(list_in_mat):
list_out_mat = []
array_in_mat = array(list_in_mat)
array_out_mat = array_in_mat.T
nb_lines = size(array_out_mat, 0)
for i_line_out in range(0, nb_lines):
array_out_line = array_out_mat[i_line_out]
list_out_line = list(array_out_line)
list_out_mat.append(list_out_line)
return list_out_mat
其他回答
只是为了好玩:如果你想把它们都做成字典的话。
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}]
等价于耶拿的解决方案:
>>> l=[[1,2,3],[4,5,6],[7,8,9]]
>>> [list(i) for i in zip(*l)]
... [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
import numpy as np
r = list(map(list, np.transpose(l)))
matrix = [[1,2,3],
[1,2,3],
[1,2,3],
[1,2,3],
[1,2,3],
[1,2,3],
[1,2,3]]
rows = len(matrix)
cols = len(matrix[0])
transposed = []
while len(transposed) < cols:
transposed.append([])
while len(transposed[-1]) < rows:
transposed[-1].append(0)
for i in range(rows):
for j in range(cols):
transposed[j][i] = matrix[i][j]
for i in transposed:
print(i)
只是为了好玩,有效的矩形假设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]]