[英]changing element in list within a list changes whole column - python
So im trying to get a paintboard like a coordinate system with the width of 10 and height of 5 so it looks like this represented by lists within lists eg [['x','x','x','x','x','x','x','x','x','x'],['x','x','x','x','x','x','x','x','x','x'],['x','x','x','x','x','x','x','x','x','x'],['x','x','x','x','x','x','x','x','x','x'],['x','x','x','x','x','x','x','x','x','x']]所以我试图得到一个像宽度为 10 和高度为 5 的坐标系的画板,所以它看起来像这样由列表中的列表表示,例如 [['x','x','x','x',' x','x','x','x','x','x'],['x','x','x','x','x','x',' x','x','x','x'],['x','x','x','x','x','x','x','x',' x','x'],['x','x','x','x','x','x','x','x','x','x'], ['x','x','x','x','x','x','x','x','x','x']]
printing it out would look like this打印出来看起来像这样
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
now I want to change one element in there so it looks like this现在我想改变其中的一个元素,所以它看起来像这样
xxcxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
xxxxxxxxxx
my code:我的代码:
class Paintboard():
def __init__(self, width, height):
self.width = width
self.height = height
extra = []
self.board = []
for x in range(0, self.width):
extra.append('x')
for y in range(0, self.height):
self.board.append(extra)
def str(self):
for x in self.board:
print(" ".join(x))
return ""
def paint(self):
self.board[0][3] = "c" # here btw x and y are switched cuz of element arrangement in self.board
test = Paintboard(10, 5)
test.paint()
test.str()
Instead of just replacing element on [3,0] it actually replaces every element in the column for some reason output:由于某种原因output实际上替换了列中的每个元素,而不是仅仅替换[3,0]上的元素:
xxxcxxxxxx
xxxcxxxxxx
xxxcxxxxxx
xxxcxxxxxx
xxxcxxxxxx
Ive been trying to find the error for a long time now in my code please help me我一直试图在我的代码中找到错误很长时间,请帮助我
self.board.append(extra)
This line appends the same object as the row to each column.此行将与行相同的 object 附加到每一列。 So if you change the object via one row, all other rows also see the effect.
因此,如果您通过一行更改 object,所有其他行也会看到效果。
You could make a copy of the row to append instead.您可以将该行复制到 append 代替。
self.board.append(extra.copy())
And your code should work你的代码应该可以工作
other way: you need to change for loop,其他方式:您需要更改 for 循环,
class Paintboard():
def __init__(self, width, height):
self.width = width
self.height = height
self.board = []
for y in range(0, self.height):
extra = []
for x in range(0, self.width):
extra.append('x')
self.board.append(extra)
def str(self):
for x in self.board:
print(" ".join(x))
return ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.