gpt4 book ai didi

python - 替换二维数组中的元素时出现奇怪的错误

转载 作者:行者123 更新时间:2023-11-30 23:31:15 25 4
gpt4 key购买 nike

in_file = open("3.8.2.txt",'r')


height = 8
width = 11
board = []
liner = []
for i in range(200):
liner.append("0")
for i in range(200):
board.append(liner)

for i in range(height):
line = in_file.readline().strip("\n").lower()
for j in range(len(line)):
board[50 + i][50 + j] = line[j]

我试图在一堆 0 周围放置一个 2d 板。不是在中间得到一个漂亮的板,而是将板的最后一行放置在板上每条线的中间。我不知道为什么。

这是输出:

00000000000000000000000000000000000000000000000000yuiqlxcnbjf000000000000000000000000
00000000000000000000000000000000000000000000000000yuiqlxcnbjf000000000000000000000000
00000000000000000000000000000000000000000000000000yuiqlxcnbjf000000000000000000000000
00000000000000000000000000000000000000000000000000yuiqlxcnbjf000000000000000000000000
00000000000000000000000000000000000000000000000000yuiqlxcnbjf000000000000000000000000

我的预期输出将是这样的:

000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000
00000000000000000letterss00000000000000000000000000000
00000000000000000letterss00000000000000000000000000000
00000000000000000letterss00000000000000000000000000000
00000000000000000letterss00000000000000000000000000000
00000000000000000letterss00000000000000000000000000000
000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000

最佳答案

实际问题在这行

for i in range(200):
board.append(liner)

您不会创建 200 个新列表并将其附加到board。相反,您将向面板中的同一列表添加 200 个引用。您应该做的是,创建线性的副本并将其附加到板中,如下所示

for i in range(200):
board.append(liner[:])

板子准备可以这样写

board = [["0"] * 200 for _ in range(200)]

关于python - 替换二维数组中的元素时出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20062530/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com