# Create a 5 x 5 matrix using a list of lists: matrix
matrix = [[col for col in range(5)] for row in range(5)]
求解。。。
为什么这么写?中间是怎样的一个过程,一个for的推导式是理解的,但是这里主要是不理解两个for之间到底是怎么个关系和逻辑在生成。
谢谢
# Create a 5 x 5 matrix using a list of lists: matrix
matrix = [[col for col in range(5)] for row in range(5)]
求解。。。
为什么这么写?中间是怎样的一个过程,一个for的推导式是理解的,但是这里主要是不理解两个for之间到底是怎么个关系和逻辑在生成。
谢谢
二维列表转置:
[row[i] for row in matrix] for i in range(matrix[0].len())]
matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]
print(matrix)
实现矩阵行列转置
print([[row[i] for row in matrix] for i in range(4)])
嵌套解析语句执行顺序同上
左边第二句 for i in range(4)是最外层
左边第一句 [row[i] for row in matrix]是最内层
而最内层 又同样划分为 for row in matrix
row[i]
因此执行顺序是
for i in range(4)
for row in matrix
row[i]
transposed = []
for i in range(4):
transposed.append([row[i] for row in matrix])
print(transposed)
创建二维列表格式:list_2d = [[0 for col in range(cols)] for row in range(rows)]
list_2d = [ [0 for i in range(5)] for i in range(5)] #创建
print(list_2d)
list_2d[0].append(3)
list_2d[0].append(5)
print(list_2d)
运行结果
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[[0, 0, 0, 0, 0, 3, 5], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]