我写了一个函数 SwapCities,它能够交换列表中的条目 3 和 4。
所以 fe [0,1,2,3,4] 应该变成 [0,1,2,4,3]。此功能完美运行,但奇怪的是我的原始列表也发生了我不想要的更改。
这是我的代码:
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
我得到以下结果:
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?!)
正如你所看到的,我原来的解决方案改变了它不应该做的事情。
我不知道为什么会这样。即使我更改代码以便将更改应用于原始列表的副本,我也会得到这个结果。有人可以解释我做错了什么吗?
IncumbentSolution = list(x for x in range(0,NumberOfCities))
print "Start"
print IncumbentSolution
print "After swap"
tmpsolution = IncumbentSolution
NewSolution = SwapCities(tmpsolution)
print NewSolution
print "Original solution"
print IncumbentSolution