下面是我的代码n = 4m = 4figures = [1,2,2]def almostTetris(n, m, figures): grid = [[0] * m] * n def shape1(count): for i in range(n): for j in range(m): if grid[i][j] == 0: print(grid[i][j]) print(grid[1][0]) print(grid[2][0]) print(grid[3][0]) grid[i][j] = count print(grid[i][j]) print(grid[1][0]) print(grid[2][0]) print(grid[3][0]) return def shape2(count): for i in range(n): for j in range(m - 2): if grid[i][j] == 0 and grid[i][j + 1] == 0 and grid[i][j + 2] == 0: grid[i][j] = grid[i][j + 1] = grid[i][j + 2] = count return for i in range(len(figures)): if figures[i] == 1: shape1(i + 1) elif figures[i] == 2: shape2(i + 1) return gridprint(almostTetris(n, m, figures))这是我打印出来的:00001111[[1, 2, 2, 2], [1, 2, 2, 2], [1, 2, 2, 2], [1, 2, 2, 2]]我的问题是如何grid[i][j] = count将第一列中的所有数字转换为 1(计数值)?我以为因为i和j都是0,所以只有第一个元素会变成1。
1 回答
HUX布斯
TA贡献1876条经验 获得超6个赞
当我第一次学习Python时,我也遇到过这个问题。问题出在这一行
grid=[[0]*m]*n
因为它不会创建一个由 0 组成的 nxm 网格,所以它实际上复制了对象:[[0]*m]
n 次以创建二维数组。因此,如果您更改此对象中的其中一个值,其他 n 个对象实例也会被编辑。尝试一些类似的事情
grid = [[0]*m for _ in range(n)]
添加回答
举报
0/150
提交
取消