我有一个功能:
def mutate(self, index):
ing1, ing2 = random.randrange(8), random.randrange(8)
while ing1 == ing2:
ing2 = random.randrange(8)
ptr = self.drinkList[index].ing[:]
ing1thr = ptr[ing1].max - ptr[ing1].perc
ing2thr = ptr[ing2].perc - ptr[ing2].min
mutatedFitness = 0
if ing1thr & ing2thr:
change = random.randrange(ing1thr if ing1thr < ing2thr else ing2thr)
ptr[ing1].perc += change
ptr[ing2].perc -= change
for x in ptr:
mutatedFitness += x.perc * x.price
mutatedFitness = 280000 - mutatedFitness
if mutatedFitness > self.drinkList[index].fitness:
self.drinkList[index].ing = ptr[:]
现在,我希望ptr是self.drinkList [index] .ing列表的副本,但在调试器中我注意到它指向对象本身而不是复制。我认为切片是避免它的方法,我在哪里弄错了?
答案 0 :(得分:0)
切片创建一个view
对象。使用copy
模块。
答案 1 :(得分:0)
扩展skrat所说的
import copy
new_list = copy.deepcopy(old_list)