[英]Python incorrect ways to add to list when generating permutations
In this example, why does this generate the correct result:在这个例子中,为什么会产生正确的结果:
nxt = path + [nums[i]]
But not:但不是:
nxt = path ; nxt += [nums[i]]
nxt = path ; nxt.append(nums[i])
def permute(nums):
def dfs(nums, path):
if not nums: # empty, done with path
all_perms.append(path)
return
for i in range(len(nums)):
nxt = path + [nums[i]]
# nxt = path ; nxt += [nums[i]]
# nxt = path ; nxt.append(nums[i])
print(nxt)
dfs(nums[:i] + nums[i+1:], nxt)
all_perms = []
dfs(nums, [])
return all_perms
In this example, why does this generate the correct result:在这个例子中,为什么会产生正确的结果:
nxt = path + [nums[i]]
This leaves path
unmodified.这使path
不变。
But not:但不是:
nxt = path ; nxt += [nums[i]]
nxt = path ; nxt.append(nums[i])
This appends nums[i]
to path
which is apparently incorrect.这将nums[i]
附加到显然不正确的path
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.