我的程序在数组中交换位置,但它们确实会恢复。你知道吗
def swapPositions(list, pos1, pos2):
list[pos1], list[pos2] = list[pos2], list[pos1]
return list
while True:
#swap positions
challanging_route = []
rand_index = random.randint(0,len(ca)-1)
rand_index2 = random.randint(0,len(ca)-1)
while rand_index == rand_index2:
rand_index2 = random.randint(0,len(ca)-1)
challanging_route = best_route
print("")
print(best_route)
a = swapPositions(challanging_route,rand_index,rand_index2)
challanging_route = a
if challanging_route == best_route:
print("same ERROR")
#calculate distance
distance_best = calculateDistance(cm,best_route)
distance_challanging = calculateDistance(cm,challanging_route)
distance_diff = distance_best - distance_challanging
print(distance_diff)
我希望我换了两个位置,但我得到了“相同的错误”。你知道吗
当您通过执行
您没有创建现有列表的不同副本:如果您更改两个列表(
challanging_route
或best_route
)中的任何一个列表中的元素,它将在另一个列表中执行相同的更改。你知道吗你想做的可能是复制你的清单:
编辑:最重要的是,你的
swapPositions
改变了它的list
参数,这意味着当你做swapPositions(challanging_route,rand_index,rand_index2)
时它实际上改变了原来的challanging_route
。因此,不需要将其分配给新列表a
。你知道吗为了清楚起见,您可能应该
简单地
在这些线处:
best_route
和challanging_route
引用内存中相同的id
。你知道吗因此当您更改对象时,两个变量(在您的例子中是
challanging_route
和best_route
)都将引用更改的对象。内存模式寻址:
获取内存地址:
因此,可以使用
copy
进行浅层复制,也可以使用deepcopy
复制较深的对象。你知道吗获取内存地址:
copy in python
相关问题 更多 >
编程相关推荐