[英]Python, making shallow copy of a list doesn't work with object attributes?
I am trying to make a shallow copy of a list, this list is stored in an object's attribute.我正在尝试制作一个列表的浅拷贝,这个列表存储在一个对象的属性中。 Even though my shallow copy is in a function it doesnt work, I tried即使我的浅拷贝在一个不起作用的函数中,我也试过了
copy.copy
temp = list(actuallist)
temp = actuallist[:]
Here is related parts of my current code这是我当前代码的相关部分
This is the object这是对象
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 = []
This is the part where I create a shallow list and change it这是我创建一个浅表并更改它的部分
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"""
Turns out i needed to copy.deepcopy() the list.结果我需要 copy.deepcopy() 列表。
Your three techniques make shallow copies of the list.你的三种技术制作了列表的浅拷贝。 So even though the list itself is unque - and you can do things like adding and removing elements on one without affecting the other - the contained objects are the same.因此,即使列表本身是独一无二的——并且您可以在不影响另一个的情况下执行诸如添加和删除元素之类的操作——所包含的对象是相同的。 temp[game.doctor.xpos][game.doctor.ypos] = "X"
changes the contained object which is still held by both lists. temp[game.doctor.xpos][game.doctor.ypos] = "X"
更改仍由两个列表持有的包含对象。
As an example, lets just put some dict
s in a list and see what happens举个例子,让我们把一些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'}
>>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.