已更改阵列还原b

2024-10-04 09:21:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我的程序在数组中交换位置,但它们确实会恢复。你知道吗

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)

我希望我换了两个位置,但我得到了“相同的错误”。你知道吗


Tags: indexlenrandomroutelistcadistancebest
2条回答

当您通过执行

challanging_route = best_route

您没有创建现有列表的不同副本:如果您更改两个列表(challanging_routebest_route)中的任何一个列表中的元素,它将在另一个列表中执行相同的更改。你知道吗

你想做的可能是复制你的清单:

challanging_route = best_route[:]

编辑:最重要的是,你的swapPositions改变了它的list参数,这意味着当你做swapPositions(challanging_route,rand_index,rand_index2)时它实际上改变了原来的challanging_route。因此,不需要将其分配给新列表a。你知道吗

为了清楚起见,您可能应该

a = swapPositions(challanging_route,rand_index,rand_index2)
challanging_route = a

简单地

swapPositions(challanging_route,rand_index,rand_index2)

在这些线处:

challanging_route = best_route

challanging_route = a

best_routechallanging_route引用内存中相同的id。你知道吗

因此当您更改对象时,两个变量(在您的例子中是challanging_routebest_route)都将引用更改的对象。

内存模式寻址:

best_route > object at 0x9cf10c < challanging_route

获取内存地址:

>>> hex(id(challanging_route))
out: 0x7f4f2fcc1588

>>> hex(id(best_route))
our: 0x7f4f2fcc1588

因此,可以使用copy进行浅层复制,也可以使用deepcopy复制较深的对象。你知道吗

import copy

challanging_route = copy.copy(best_route)

获取内存地址:

>>> hex(id(challanging_route))
out: 0x7f4f2fcc1588

>>> hex(id(best_route))
our: 0x7f4f2fcc1587

copy in python

相关问题 更多 >