[英]Why does a list change when i change another?
the "startboard" list changes when im not doing it当我不这样做时,“启动板”列表会发生变化
def moves(board, player):
boardlist=[]
for x in range(7):
newboard=board
if board[5][x]==0:
place=0
if player:
newboard[place][x]=1
else:
newboard[place][x]=2
boardlist.append(newboard)
return boardlist
startboard=[[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]]
moves(startboard, True)
i added indexes at newboard=board[:][:]
and it still didnt work我在
newboard=board[:][:]
添加了索引,但它仍然没有用
how can i stop the startboard list from changing?我怎样才能阻止启动板列表发生变化?
try:尝试:
from copy import deepcopy
def moves(board, player):
boardlist=[]
for x in range(7):
newboard = deepcopy(board)
if board[5][x]==0:
place=0
if player:
newboard[place][x]=1
else:
newboard[place][x]=2
boardlist.append(newboard)
return boardlist
startboard=[[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]]
moves(startboard, True)
You can find explanation here: https://www.geeksforgeeks.org/copy-python-deep-copy-shallow-copy/你可以在这里找到解释: https://www.geeksforgeeks.org/copy-python-deep-copy-shallow-copy/
newboard=board[:][:]
is a shallow copy, it has the same references as the original object. The docs explain the difference between shallow and deep copies: newboard=board[:][:]
是一个浅拷贝,它与原始 object 具有相同的引用。文档解释了浅拷贝和深拷贝之间的区别:
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
浅拷贝和深拷贝之间的区别仅与复合对象(包含其他对象的对象,如列表或 class 实例)有关:
A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
浅拷贝构造一个新的化合物 object,然后(在可能的范围内)向其中插入对原始对象中找到的对象的引用。
A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
深拷贝构造一个新的化合物 object,然后递归地将在原始对象中找到的对象的副本插入其中。
Here's a little demonstration:这是一个小演示:
import copy
a = [1, 2, 3]
b = [4, 5, 6]
c = [a, b]
Using normal assignment operatings to copy:使用正常的分配操作来复制:
d = c
print id(c) == id(d) # True - d is the same object as c
print id(c[0]) == id(d[0]) # True - d[0] is the same object as c[0]
Using a shallow copy:使用浅拷贝:
d = copy.copy(c)
print id(c) == id(d) # False - d is now a new object
print id(c[0]) == id(d[0]) # True - d[0] is the same object as c[0]
Using a deep copy:使用深拷贝:
d = copy.deepcopy(c)
print id(c) == id(d) # False - d is now a new object
print id(c[0]) == id(d[0]) # False - d[0] is now a new object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.