我如何在python中制作网格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41910947/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:50:19  来源:igfitidea点击:

How do i make a grid in python?

pythongrid

提问by SollyBunny

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:

它不起作用,我不知道为什么。这就是我放置 5 个宽度和 5 个高度时得到的结果:

['.', '.', '.', '.', '.']
['.', '.', '.', '.', '.']
['.', '.', '.', '.', '.']
['.', '.', '.', '.', '.']
['.', '.', '.', '.', '.']

That's fine and all but when i change the bottom left dot by using this: grid[0][0] = "a". This happens:

这很好,但是当我使用以下命令更改左下角的点时:grid[0][0] = "a"。有时候是这样的:

['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

它认为“行”列表是一个标签,当它被清楚地编码为不是请帮助我解决这个问题

采纳答案by SollyBunny

Use list()

使用列表()

gridline = []
for i in range(5):
    gridline.append("")
grid = []
for i in range(5):
    grid.append(list(gridline))

回答by DeepSpace

for i in range(height):
    grid.append(row)

This forloop appends the same rowlist to the gridlist (actually it appends 5 different references to the samelist).

这个for循环将相同的row列表附加到grid列表中(实际上它向同一个列表附加了 5 个不同的引用)。

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:

通过查看以下 2 个示例中的内部列表的内存地址进行验证:

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

回答by Trigger-Me-Elmo

Just use this.

就用这个。

    width = int(input("how wide "))
    height = int(input("how tall "))
    grid = []
    i = int(0)
    for i in range(width):
        grid.append("_")
    for i in range(height):
        print(grid)