我想使用两个for循环来生成一个空的二维数组。我找到了一个可行的方法,看起来像这样:
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
。 - dspencer