变量相同但不应该? Python

Variables are the same but shouldn't be? Python

我遇到了一些问题,因为变量被设置为不应该设置的相同,我不明白他们为什么要这样做。在我的例子中,LCT 和 MCT 被设置为函数中生成的最后一条路线,但我只有在路线分别小于或大于最低成本或最高成本时才设置它们。基本上,我创建了一个 0-13 整数的伪随机列表作为城市标签,并使用 i-by-j 数组查找查找它们之间的距离,其中值表示从城市 i 到城市旅行时的距离j.这是我的 TSP 项目的一部分。这里有一些代码供参考:

import random

def distance(x1, y1, x2, y2):
     """
     Finds the distance between two points with coordinates (x1, y1) and (x2, y2)
     :param x1: x-coordinate of first point
     :type x1: float or int
     :param y1: y-coordinate of first point
     :type y1: float or int
     :param x2: x-coordinate of second point
     :type x2: float or int
     :param y2: y-coordinate of second point
     :type y2: float or int
     :return: distance between two points
     :rtype: float
     """
     return (((x2-x1)**2) + ((y2-y1)**2)) ** 0.5

def shuffle(idxs):
    """
    Performs random swaps n times with random seeded generator
    :param idxs: Set of items to choose from
    :type idxs: list, tuple, or dict
    :return: modified idxs
    :rtype modified idxs: type(idxs)
    """
    n = 32
    for k in range(n):
        random.seed()
        a, b = random.randint(0, 13), random.randint(0, 13)
        swap(idxs, a, b)
        # print(idxs)
    return idxs


def swap(mylist, a, b):
    """
    Swaps two values
    :param mylist: order of things to choose from
    :type mylist: list, tuple, or dict
    :param a: first index
    :type a: list/tuple: int; dict: key
    :param b: second index
    :type b: list/tuple: int; dict: key
    :return: none; edits items in place
    """
    temp = mylist[a]
    mylist[a] = mylist[b]
    mylist[b] = temp

mat = [[0.430796749, 0.660341257],
      [0.869607109, 0.145710154],
      [0.272249997, 0.281035268],
      [0.310050105, 0.717362826],
      [0.847481151, 0.505130257],
      [0.054921944, 0.597324847],
      [0.565507064, 0.578311901],
      [0.578311901, 0.636552793],
      [0.170565332, 0.160881561],
      [0.800726237, 0.384045138],
      [0.622627218, 0.957622127],
      [0.608021461, 0.736718151],
      [0.628737267, 0.622146623],
      [0.665929436, 0.720342005]]

distances = [[distance(x1=mat[i][0], y1=mat[i][1],
                 x2=mat[j][0], y2=mat[j][1]) for j in range(14)] for i in range(14)]

route = [i for i in range(14)]
bigN = 1000
LC = 100
MC = 0

for j in range(bigN):
    this_dist = 0
    route = shuffle(route)
    # print('Route:', route)

    # Get the distance for the route
    for stop in range(len(route)):
        if stop != len(route) - 1:  # if its not the last node
            this_dist += distances[route[stop]][route[stop + 1]]
        else:  # Add cost from last item to first item
            this_dist += distances[route[stop]][route[0]]
    # print('Distance:', this_dist)

    # Update min/max
    if this_dist < LC:
        LC = this_dist
        LCT = route
        print('New low:', LCT, 'Distance:', LC)
    elif this_dist > MC:
        MC = this_dist
        MCT = route
        print('New high:', MCT, 'Distance:', MC)

print('Last route:', route, 'Last distance:', this_dist)

# Output
print('Least cost:', LC)
print('Least cost trip:', LCT)
print('Most cost:', MC)
print('Most cost trip:', MCT)

如果您只是将其复制并粘贴到 IDE 和 运行 中,您就会明白我的意思。 LCT 和 MCT 被设置为最后生成的路线(即使它不是 least/most 成本行程),当我只在当前路线 shorter/longer 比当前 least/most 成本。为什么会发生这种情况,我该怎么做才能将其正确设置为 LCT/MCT?如果这是一个很长的 post,我感到非常困惑和抱歉,但我无法弄清楚。我正在使用 Python 3.7,如果有帮助的话。编辑:问题澄清。

我希望 LCT/MCT 至少会有所不同,因为它们会有不同的路线和与之相关的不同距离。我的问题是变量被设置为最后生成的路由,不管它实际上是 shorter/longer 还是实际的 shortest/longest 路由。每次当前路线 shorter/longer 比实际 shortest/longest 路线,我让它打印出新路线和新的最短距离。 LCT/MCT 应设置为最后打印的相应内容。

最后编辑:jasonharper 在评论中的解决方案有效(抱歉,如果我删除了用户名,您在编辑模式下看不到它们,而且我没有足够的代表来评论 post)。当我将它们复制到 LCT/MCT 时,我只需要将 [:] 添加到 routes 的末尾。谢谢!

基本上路线是可变的,每次都会改变。当您设置 LCT/MCT 时,它是指向路由的指针。您可以使用@jasonharper 的建议并更新代码如下:

# Update min/max
if this_dist < LC:
    LC = this_dist
    LCT = route[:]
    print('New low:', LCT, 'Distance:', LC)
elif this_dist > MC:
    MC = this_dist
    MCT = route[:]
    print('New high:', MCT, 'Distance:', MC)