赞
踩
做题时遇到创建数组时遇到一个小问题,如下:
grid=[
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]]
seen=[[0]*len(grid[0]) for _ in range(len(grid))]
print(seen)
seen[0][0]=1
print(seen)
a=[[0]*len(grid[0])]*len(grid)
print(a)
a[0][0]=1
print(a)
输出结果如下:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[[1, 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, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]
可见第一种创建数组的方法是正确的,而第二种给一个元素赋值,对应的所有行相同列都会赋值。
创建一个4*5的二维数组正确格式如下:
ls=[[0]*5 for _ in range(4)]
而以下面这种方式创建二维数组时赋值会出现错误:
ls=[[0]*5]*4
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。