Python 3.x Python:for循环多次只保存最后一个对象时遇到问题
我尝试从一个新行分隔的文本文件加载以下代码。它存储由颜色、大小和种类组成的苹果对象(每一个都在一条换行线上)。奇怪的是,load函数可以工作,但它返回的所有加载对象都与上次加载的对象相同(但它根据文本文件中的行将正确数量的对象放入列表中。尽管如此,append附近的打印显示了每个对象的正确读取数据 我不确定哪里出了问题,如何纠正Python 3.x Python:for循环多次只保存最后一个对象时遇到问题,python-3.x,text-files,Python 3.x,Text Files,我尝试从一个新行分隔的文本文件加载以下代码。它存储由颜色、大小和种类组成的苹果对象(每一个都在一条换行线上)。奇怪的是,load函数可以工作,但它返回的所有加载对象都与上次加载的对象相同(但它根据文本文件中的行将正确数量的对象放入列表中。尽管如此,append附近的打印显示了每个对象的正确读取数据 我不确定哪里出了问题,如何纠正 def loadInApplesTheOtherWay(filename): tempList = [] #make a tempList and load
def loadInApplesTheOtherWay(filename):
tempList = []
#make a tempList and load apples from file into it
with open(filename,"r") as file:
#file goes, colour \n size \n kind \n repeat...
lines = file.read().splitlines()
count = 1
newApple = apple()
for line in lines:
if count % 3 == 1:
newApple.colour = line
if count % 3 == 2:
newApple.size = line
if count % 3 == 0:
newApple.kind = line
tempList.append(newApple)
print(newApple)
count +=1
return tempList
您需要将
newApple=apple()
移动到循环的内部。newApple
只是一个对象引用
>>> list(map(id, tempList))
上行将显示所有苹果都具有相同的id。由于上次修改的newApple
位于文件末尾,因此templast
与上次修改的苹果对象相同
要使其有所不同,您需要deepcopy
对象,例如templast.append(copy.deepcopy(newApple))
有关详细信息,请参阅
或者您可以动态创建对象,您不必在for循环之前分配newApple
def loadInApplesTheOtherWay(filename):
tempList = []
#make a tempList and load apples from file into it
with open(filename,"r") as file:
#file goes, colour \n size \n kind \n repeat...
lines = file.read().splitlines()
count = 1
for line in lines:
if count % 3 == 1:
colour = line
if count % 3 == 2:
size = line
if count % 3 == 0:
kind = line
newApple = Apple(colour, size, kind)
tempList.append(newApple)
print(newApple)
count +=1
return tempList
但如果我这样做,它不会完全创建每个apple对象,因为只有在每三个循环之后,apple才会完全加载到。。。