Chainguys 2021-06-15 09:22 采纳率: 93.6%

# 用Python创建一个矩阵，求详解。。。

``````# Create a 5 x 5 matrix using a list of lists: matrix
matrix = [[col for col in range(5)] for row in range(5)]``````

• 写回答

#### 1条回答默认 最新

• 小P聊技术 2021-06-15 09:26
关注

二维列表转置：
[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]]

``````

列表解析详解传送门(https://www.cnblogs.com/liu-shuai/p/6098227.html)

本回答被题主选为最佳回答 , 对您是否有帮助呢?
评论

#### 悬赏问题

• ¥40 求一款能支持ios15以上的屏蔽越狱插件。比较好用的
• ¥15 C++ QT对比内存字符（形式不定）
• ¥30 C++第三方库libiconv 远程安装协助