让我们来:
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)]
当前回答
有三种选择:
1. Zip地图
solution1 = map(list, zip(*l))
2. 列表理解
solution2 = [list(i) for i in zip(*l)]
3.For循环附加
solution3 = []
for i in zip(*l):
solution3.append((list(i)))
查看结果:
print(*solution1)
print(*solution2)
print(*solution3)
# [1, 4, 7], [2, 5, 8], [3, 6, 9]
其他回答
也许不是最优雅的解决方案,但这里有一个使用嵌套while循环的解决方案:
def transpose(lst):
newlist = []
i = 0
while i < len(lst):
j = 0
colvec = []
while j < len(lst):
colvec.append(lst[j][i])
j = j + 1
newlist.append(colvec)
i = i + 1
return newlist
有三种选择:
1. Zip地图
solution1 = map(list, zip(*l))
2. 列表理解
solution2 = [list(i) for i in zip(*l)]
3.For循环附加
solution3 = []
for i in zip(*l):
solution3.append((list(i)))
查看结果:
print(*solution1)
print(*solution2)
print(*solution3)
# [1, 4, 7], [2, 5, 8], [3, 6, 9]
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)
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])