Print 打印正确的值,但将不同的值附加到列表
Print prints the right value but the appends different value to list
我正在尝试在线编写回溯问题的解决方案。
我遇到了一个非常奇怪的代码问题。
打印语句似乎打印了我想要的确切数组,但是当两行连续时,另一个数组被附加到列表中
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def backtrack(index):
if index==len(nums):
print(nums)
permutations.append(nums)
else:
for i in range(index,len(nums)):
temp = nums[index]
nums[index] = nums[i]
nums[i] = temp
backtrack(index+1)
temp = nums[index]
nums[index] = nums[i]
nums[i] = temp
permutations = []
backtrack(0)
return permutations
预期输出如下所示
打印语句打印
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
但是我在排列数组中看到的值是
[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
这非常奇怪。有人可以帮我解决这个问题吗?
所以,我认为在 python 中更改一个列表会自动更改另一个列表。
因此,当我尝试执行 permutations.append(nums) 然后更改 nums 时,排列也会被修改。
所以解决方案是 permutations.append(list(nums))。
当您调用 permutations.append(nums)
时,您并没有附加 nums
的 copy -- 您附加的是对实际 nums
对象。这意味着如果 nums
发生变化,所有引用也会发生变化,因为它们都是 同一个对象 .
代码对所有排列重复使用同一个列表 nums
。因此 permutations
中的所有元素都指向同一个列表并且是相同的。
我正在尝试在线编写回溯问题的解决方案。
我遇到了一个非常奇怪的代码问题。
打印语句似乎打印了我想要的确切数组,但是当两行连续时,另一个数组被附加到列表中
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def backtrack(index):
if index==len(nums):
print(nums)
permutations.append(nums)
else:
for i in range(index,len(nums)):
temp = nums[index]
nums[index] = nums[i]
nums[i] = temp
backtrack(index+1)
temp = nums[index]
nums[index] = nums[i]
nums[i] = temp
permutations = []
backtrack(0)
return permutations
预期输出如下所示 打印语句打印
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
但是我在排列数组中看到的值是
[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
这非常奇怪。有人可以帮我解决这个问题吗?
所以,我认为在 python 中更改一个列表会自动更改另一个列表。 因此,当我尝试执行 permutations.append(nums) 然后更改 nums 时,排列也会被修改。
所以解决方案是 permutations.append(list(nums))。
当您调用 permutations.append(nums)
时,您并没有附加 nums
的 copy -- 您附加的是对实际 nums
对象。这意味着如果 nums
发生变化,所有引用也会发生变化,因为它们都是 同一个对象 .
代码对所有排列重复使用同一个列表 nums
。因此 permutations
中的所有元素都指向同一个列表并且是相同的。