我正在尝试制作列表的浅表副本,此列表存储在对象的属性中。即使我的浅拷贝在一个函数中它不起作用,我试过
copy.copy
temp = list(actuallist)
temp = actuallist[:]
以下是我当前代码的相关部分
这是对象
class Game:
tiles = []
daleks = []
rawtile = ""
height = 20
width = 20
tilesize = 32
gamemap = "default"
status = 0
doctor = ""
screen = ""
clock = pygame.time.Clock()
def __init__(self,height,width,tilesize,gamemap):
self.height = height
self.width = width
self.tilesize = 32
self.gamemap = gamemap
self.status = 0
size = (tilesize*width, tilesize*height)
self.screen = pygame.display.set_mode(size)
pygame.display.set_caption("Doctor Who vs Daleks")
def teleportDoctorIn(self,classname):
self.doctor = classname
def releaseDalek(self,x):
self.daleks.append(x)
def resetDaleks(self):
daleks = []
这是我创建浅层列表并进行更改的部分
def updateMap(x,y):
temp = game.tiles[:]
"""SET DOCTOR COORDS"""
temp[game.doctor.xpos][game.doctor.ypos] = "X"
game.doctor.move(x,y)
temp[game.doctor.xpos][game.doctor.ypos] = "D"
"""LETS MOVE DALEKS"""
原来我需要copy.deepcopy()列表。
答案 0 :(得分:0)
您的三种技术会对列表进行浅层复制。因此,即使列表本身是unque - 并且您可以执行诸如在一个上添加和删除元素而不影响另一个的事情 - 所包含的对象是相同的。 temp[game.doctor.xpos][game.doctor.ypos] = "X"
更改两个列表仍然保留的包含对象。
举个例子,让我们在列表中放一些dict
,看看会发生什么
>>> import copy
>>> d1={1:'one', 2:'two'}
>>> d2={3:'three', 4:'four'}
# create a list then copy it
>>> l1=[d1, d2]
>>> l2=l1[:]
# l1 and l2 are different, but their members are the same
>>> id(l1) == id(l2)
False
>>> id(l1[0]) == id(l2[0])
True
# and if you change the objects in l2, they change l1
>>> l1[0]
{1: 'one', 2: 'two'}
>>> l2[0][5]='five'
>>> l1[0]
{1: 'one', 2: 'two', 5: 'five'}
# but a deep copy copies the contained objects also so no problem
>>> l3=copy.deepcopy(l1)
# the contained objects are not the same
>>> id(l1[0]) == id(l3[0])
False
# and changing one does not affect the other
>>> l1[0]
{1: 'one', 2: 'two', 5: 'five'}
>>> l3[0]
{1: 'one', 2: 'two', 5: 'five'}
>>> l3[0][6] = 'six'
>>>
>>> l1[0]
{1: 'one', 2: 'two', 5: 'five'}
>>> l3[0]
{1: 'one', 2: 'two', 5: 'five', 6: 'six'}
>>>