[英]Python list class seems to have entangled indices
我是 python 的新手,在我的第一个项目中遇到了一些意想不到的行为。
我制作了一个将坐标字典转换为列表的类。 在我尝试在初始化后更改坐标之前,它似乎工作正常。
我想沿一个索引移动所有坐标(索引 1 变为 2,0 变为 1)并在索引 0 中放置一个新坐标。但是,当我在移动其余坐标后更改索引 0 时,索引 1 也会更改。
some_coords = [{'x': 0, 'y': 0}, {'x': 1, 'y': 0}, {'x': 1, 'y': 1}]
class coord:
def __init__(self, x, y):
self.x = x
self.y = y
class coord_list:
def __init__(self):
self.body = [coord(some_coords[i].get('x'), some_coords[i].get('y')) for i in range (len(some_coords))]
snake = coord_list()
print("printing original snake coordinates")
for i in range(len(snake.body)):
print(f"At index {i}: x : {snake.body[i].x}, y : {snake.body[i].y} ")
print("shifting all indexes forward, except index 0")
for i in range(len(snake.body) -1, 0, -1):
snake.body[i] = snake.body[i-1]
print("printing snake coordinates")
for i in range(len(snake.body)):
print(f"At index {i}: x : {snake.body[i].x}, y : {snake.body[i].y} ")
print("moving index 0 to x : 0, y : 1")
snake.body[0].y += 1
print("printing snake coordinates")
for i in range(len(snake.body)):
print(f"At index {i}: x : {snake.body[i].x}, y : {snake.body[i].y} ")
输出:
printing original snake coordinates
At index 0: x : 0, y : 0
At index 1: x : 1, y : 0
At index 2: x : 1, y : 1
shifting all indexes forward, except index 0
printing snake coordinates
At index 0: x : 0, y : 0
At index 1: x : 0, y : 0
At index 2: x : 1, y : 0
moving index 0 to x : 0, y : 1
printing snake coordinates
At index 0: x : 0, y : 1
At index 1: x : 0, y : 1
At index 2: x : 1, y : 0
为什么修改索引 0 后索引 0 和 1 处的 y 值都发生了变化,有没有办法避免这种情况?
分配对象不会复制它。 所以在转变之后, snake.body[0]
和snake.body[1]
都指向同一个coord
对象。 当您修改该对象的x
属性时,它会反映在两个索引中。
要解决这个问题,您需要创建新对象:
for i in range(len(snake.body) -1, 0, -1):
snake.body[i] = coord(snake.body[i-1].x, snake.body[i-1].y)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.