Python列表类似乎有纠缠的索引
我是python新手,在我的第一个项目中遇到了一些意想不到的行为 我创建了一个类,将坐标字典转换为列表。在我尝试在初始化后更改坐标之前,它似乎工作得很好 我想沿着一个索引移动所有坐标(索引1变为2,0变为1),并在索引0中放置一个新坐标。但是,当我在移动其余部分后更改索引0时,索引1也会更改Python列表类似乎有纠缠的索引,python,arrays,Python,Arrays,我是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__(sel
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)