【发布时间】:2020-04-03 08:36:22
【问题描述】:
我正在尝试使用 to 循环生成一个空的二维数组。我找到了一种可行的方法,它看起来像这样:
rows = 5
cols = 5
grid1 = []
grid1 = [[0 for i in range(cols)] for j in range(rows)]
print(grid1)
输出:
[[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]]
但是,当我尝试以“正常”语法编写 for 循环时,它会引发错误。为什么我不能用正常的语法写?
rows = 5
cols = 5
grid2 = []
for i in range(rows):
for j in range(cols):
grid2[i][j] = 0
print(grid2)
输出:
Exception has occurred: IndexError
list index out of range
File "C:\Users\Bruker\Downloads\test.py", line 8, in <module>
grid2[i][j] = 0
【问题讨论】:
-
您不能分配给列表中超出列表当前长度的索引。编写列表理解的等效方法是使用
append。
标签: python arrays multidimensional-array