[英]Nested List Comprehensions transpose matrix
I just started out my journey with Python and I can't figure out how this loop transposes the matrix!我刚开始我的 Python 之旅,我不知道这个循环是如何转置矩阵的! Can someone give a detailed explanation?有人可以给出详细的解释吗?
matrix = [ [1,2,3,4], [5,6,7,8], [9,10,11,12] ]
[[row[i] for row in matrix] for i in range(4)]
Maybe it will help to write the comprehension as nested loops?也许将理解编写为嵌套循环会有所帮助?
It is equivalent to:它相当于:
transposed = []
for i in range(4):
col = []
for row in matrix:
col.append(row[i])
transposed.append(col)
print(transposed)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.