这是按引用调用,错误还是其他示例? [重复]

问题描述 投票:0回答:3
我正在编写一个小程序来创建排列列表。我读到了algorithm on wikipedia

我的算法基本上采用最初排序的数字列表,并对其进行置换。然后,它将这个新排列添加到列表中。找到所有排列后,它将返回包含所有排列的列表的列表。它非常适合打印出预期的结果,但是当我尝试将这些结果添加到列表中时,事情会变得有些有趣。

我注意到,每次找到下一个排列并将其附加到后,先前的列表元素都会更新为新的排列。因此,最后,返回的是一个列表,其中包含一堆相同排列的副本(恰好是最后一个排列)。

我已经阅读过Python是按值传递,按引用传递,而且我也没有阅读过。我不够聪明,无法与这些人中的任何一个争论,但是我想知道为什么我的程序正在这样做,以及如何纠正它:

def lexi_order(nums): permutations = [] length = len(nums) while True: # find largest index i such that nums[i] < nums[i + 1] exists = False for j, elem in enumerate(nums): # check if last element if j == length - 1: break if elem < nums[j + 1]: i = j exists = True if not exists: break # find largest index k, such that i < k AND nums[i] < nums[k] for j in range(i + 1, length): if nums[j] > nums[i]: k = j # swap order of nums[i] and nums[k] nums[i], nums[k] = nums[k], nums[i] # reverse order of elements starting at position i+1 to_reverse = nums[i+1:][::-1] nums[i+1::] = to_reverse permutations.append(nums) print(permutations) return permutations

python pass-by-reference
3个回答
1
投票
您正在遍历循环的每个迭代中修改输入(nums),然后继续在permutations中添加对输入的引用。要解决此问题,请在循环开始时复制nums,并使用它代替内部的所有原始内容。

1
投票
[将nums附加到permutations时,是对其附加一个引用,而不是复制所有数据。修改nums时,它到处都会被修改。 Python是通过引用传递的。如果您对变量进行了更改(不要与重新分配变量混淆),那么该更改将在所有地方得到体现。

1
投票
您需要复制所传递的nums,否则您需要处理所传递的参考。例如:

def lexi_order(nums): permutations = [] nums = list(nums) # We are now working on a copy, and won't mutate the original whatsoever. length = len(nums) ...

© www.soinside.com 2019 - 2024. All rights reserved.