问题
This is my code
width = int(input("How wide?"))
height = int(input("How high?"))
grid = []
row = []
bak = "."
for i in range(width):
row.append(bak)
for i in range(height):
grid.append(row)
while True:
for i in range(len(grid)):
print(grid[i])
It's not working and i don't know why. This is what i get when i put 5 width and 5 height:
['.', '.', '.', '.', '.']
['.', '.', '.', '.', '.']
['.', '.', '.', '.', '.']
['.', '.', '.', '.', '.']
['.', '.', '.', '.', '.']
That's fine and all but when i change the bottom left dot by using this: grid[0][0] = "a". This happens:
['a', '.', '.', '.', '.']
['a', '.', '.', '.', '.']
['a', '.', '.', '.', '.']
['a', '.', '.', '.', '.']
['a', '.', '.', '.', '.']
It thinks the "row" list is a tag when it's clearly coded not to be Please help me on how to fix this problem
回答1:
for i in range(height):
grid.append(row)
This for loop appends the same row list to the grid list (actually it appends 5 different references to the same list).
Instead, you should append a new, different list:
for i in range(height):
grid.append([])
Verify by viewing the memory addresses of the inner lists in these 2 examples:
grid = []
row = []
for i in range(5):
grid.append(row)
for li in grid:
print(id(li))
# 92532104
# 92532104
# 92532104
# 92532104
# 92532104
compared to
grid = []
for i in range(5):
grid.append([])
for li in grid:
print(id(li))
# 80801224
# 80801160
# 80669704
# 80381192
# 80380488
回答2:
Use list()
gridline = []
for i in range(5):
gridline.append("")
grid = []
for i in range(5):
grid.append(list(gridline))
来源:https://stackoverflow.com/questions/41910947/how-do-i-make-a-grid-in-python