在这种情况下,循环如何转置矩阵?

时间:2018-04-20 06:31:34

标签: python python-3.x list-comprehension

matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
]

**[[row[i] for row in matrix] for i in range(4)]**

这个循环如何转置矩阵,请详细解释,如果可能的话,在每个循环之后步骤。

1 个答案:

答案 0 :(得分:1)

您从右到左展开列表推导:

matrix = [[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12]]

inver = [[row[i] for row in matrix] for i in range(4)]

展开后:

k = []
for i in range(4):
    l = []
    for row in matrix:
        l.append(row[i])
    k.append(l)

输入一些打印陈述来弄清楚。请参阅How to debug small programs (#1)并阅读Converting List Comprehensions to For Loops in Python

作为旁注 - 为什么来自官方教程页面来解释它?为什么不引用它们?

https://docs.python.org/3/tutorial/datastructures.html#nested-list-comprehensions