跨递归调用的python列表范围
我在python3中编写了一个递归置换生成器:跨递归调用的python列表范围,python,python-3.x,list,Python,Python 3.x,List,我在python3中编写了一个递归置换生成器: def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ ret = [] n = len(nums) def dfs(temp, visited): if len(temp) == n: ret.append(temp[:])
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
ret = []
n = len(nums)
def dfs(temp, visited):
if len(temp) == n:
ret.append(temp[:])
return
for i in range(n):
if not visited[i]:
visited[i] = True
temp.append(nums[i])
dfs(temp, visited)
# Cannot be:
# temp = temp[:-1]
del temp[-1]
visited[i] = False
dfs([], [False for _ in range(n)])
return ret
我最初在递归dfs返回后使用了temp=temp[:-1]
,但这似乎不起作用。显式使用del temp[-1]
工作
我不明白为什么会这样,请解释一下好吗 赋值给函数内部的局部变量对外部世界没有影响:
def foo(lst):
lst = [1, 2, 3]
L = [1]
foo(L)
print(L) # still [1]
修改传入的变量会:
def foo(lst):
lst.append(4)
L = [1]
foo(L)
print(L) # [1, 4]
在您的情况下,
deltemp[-1]
会更改正在传递的列表。在您的代码中,只有一个列表被分配给temp
,它以[]
开头temp=temp[:-1]
创建一个新的独立列表。分配给函数内部的局部变量对外部世界没有影响:
def foo(lst):
lst = [1, 2, 3]
L = [1]
foo(L)
print(L) # still [1]
修改传入的变量会:
def foo(lst):
lst.append(4)
L = [1]
foo(L)
print(L) # [1, 4]
在您的情况下,
deltemp[-1]
会更改正在传递的列表。在您的代码中,只有一个列表被分配给temp
,它以[]
开头temp=temp[:-1]
创建一个新的独立列表。能否修复代码块中的缩进?请使用示例输入、预期输出和实际输出更新问题。能否修复代码块中的缩进?请使用示例输入、预期输出和实际输出更新问题。