我正在编写以下程序,以便从给定的列表中生成所有可能的排列。
def permute(self, nums: List[int]) -> List[List[int]]:
def __permute(nums, n, chosen, perms):
if len(perms) == n:
print(perms)
else:
for i in range(n):
if chosen[i]:
continue
else:
chosen[i] = True
perms.append(nums[i])
__permute(nums, n, chosen, perms)
perms.pop()
chosen[i] = False
n = len(nums)
__permute(nums, n, [False]*n, [])例如:
Input: [1,2,3]
Output:
[1,2,3]
[1,3,2]
[2,1,3]
[2,3,1]
[3,1,2]
[3,2,1]这一次,我想添加列表中的所有排列并返回它:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]下面是我的代码:
def permute(self, nums: List[int]) -> List[List[int]]:
def __permute(nums, n, chosen, perms,res):
if len(perms) == n:
res.append(perms)
else:
for i in range(n):
if chosen[i]:
continue
else:
chosen[i] = True
perms.append(nums[i])
__permute(nums, n, chosen, perms, res)
perms.pop()
chosen[i] = False
n = len(nums)
res = []
__permute(nums, n, [False]*n, [], res)
return res问题是,输出中充满了空列表。
Input: [1,2,3]
Output:
[
[],
[],
[],
[],
[],
[]
]我通过将res.append(perms)替换为res.append(perms[:])修复了这个错误,但我不明白它为什么会起作用。
我还打印了每个perms的id(),并注意到一些奇怪的事情:
>>> print(id(perms))
>>>
140093677843328
140093677843328
140093677843328
140093677843328
140093677843328
140093677843328
>>> print(id(perms[:]))
>>>
140689610181440
140689610145600
140689610145600
140689610145600
140689610145600
140689610145600有没有人对这种行为有什么解释?
发布于 2020-07-22 17:48:15
perms每次都是相同的对象,但是当您执行perms[:]时,您正在创建perms的副本(这是一个独立于perms的对象)。
res ( list )存储对perms的引用,因此如果更改了perms,同样的内容也会反映在list res上。
但是,执行res[:]会为您提供perms的副本(这是一个不同的对象),如上所述。
https://stackoverflow.com/questions/63031316
复制相似问题