为什么我的原始列表更改? [英] Why does my original list change?

查看:93
本文介绍了为什么我的原始列表更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个函数SwapCities,它能够将列表中的条目3和4交换。

所以f.e. [0,1,2,3,4]应该变成[0,1,2,4,3]。这个功能完美的工作,但奇怪的是我的原始列表也改变了我不想要的。

I a wrote a function SwapCities that is able to swap entries 3 and 4 in a list.

这是我的代码:

This is my code:






def SwapCities(solution): n = 3##randint(0,NumberOfCities-1) m = 4##randint(0,NumberOfCities-1) result = solution temp1 = solution[n] temp2 = solution[m] result[n] = temp2 result[m] = temp1 return result




我得到以下结果:

print "Start" IncumbentSolution = list(x for x in range(0,NumberOfCities)) print IncumbentSolution print "After swap" NewSolution = SwapCities(IncumbentSolution) print NewSolution print "Original solution" print IncumbentSolution

I get the following result:

正如你可以看到我原来的解决方案改变了它不应该做的。

How many cities? 8 Start [0, 1, 2, 3, 4, 5, 6, 7] After swap [0, 1, 2, 4, 3, 5, 6, 7] Original solution [0, 1, 2, 4, 3, 5, 6, 7] (why did this change?!)

我不知道为什么会发生这种情况。即使当我更改代码以使更改应用于原始列表的副本时,我也会得到此结果。有人可以解释我做错了什么?

As you can see my original solution changed which it should not do.

I have no clue why this happens. Even when I change the code such that the changes to are applied to a copy of the original list I get this result. Could someone explain what I am doing wrong?


推荐答案

SwapCities mutating solution 的内容。
由于 solution 指向与 IncumbentSolution 相同的列表,所以 IncumbentSolution 也被修改。

解决方案

保留 IncumbentSolution

SwapCities is mutating the contents of solution. Since solution points to the same list as IncumbentSolution, the values inside IncumbentSolution are altered too.

tmpsolution = list(IncumbentSolution)

制作原始列表的浅表副本。由于 IncumbentSolution 的内容是不可变的数字,所以浅拷贝就足够了。如果包含的内容(比如说 dicts )也被突变,那么您需要对该列表进行深层次的复制:

makes a shallow copy of the the original list. Since the contents of IncumbentSolution are immutable numbers, a shallow copy suffices. If the contents included, say, dicts which were also being mutated, then you would need to make a deep copy of the list:

import copy
tmpsolution = copy.deepcopy(IncumbentSolution)

这篇关于为什么我的原始列表更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆