Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
跨递归调用的python列表范围_Python_Python 3.x_List - Fatal编程技术网

跨递归调用的python列表范围

跨递归调用的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[:])

我在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[:])
            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]
创建一个新的独立列表。

能否修复代码块中的缩进?请使用示例输入、预期输出和实际输出更新问题。能否修复代码块中的缩进?请使用示例输入、预期输出和实际输出更新问题。