Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/kubernetes/5.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.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 3.x 为什么参数值在调用后存储在我的函数中?_Python 3.x - Fatal编程技术网

Python 3.x 为什么参数值在调用后存储在我的函数中?

Python 3.x 为什么参数值在调用后存储在我的函数中?,python-3.x,Python 3.x,我在Python中看到了一些我以前从未见过的东西 我正在编写一个动态编程教程,以找到两个字符串之间最长的公共子序列。澄清一下,我不想在这个问题上得到帮助。我的问题是参数accs存储了以前函数调用的返回值 代码如下: def lcs(str1 = '', str2 = '', accs = []): if str1 and str2: str1 = list(str1) str2 = list(str2) for char1 in str1:

我在Python中看到了一些我以前从未见过的东西

我正在编写一个动态编程教程,以找到两个字符串之间最长的公共子序列。澄清一下,我不想在这个问题上得到帮助。我的问题是参数accs存储了以前函数调用的返回值

代码如下:

def lcs(str1 = '', str2 = '', accs = []):
    if str1 and str2:
        str1 = list(str1)
        str2 = list(str2)
        for char1 in str1:
            for char2 in str2:
                if char1 == char2:
                    accs.append(char1)
                    str1.remove(char1)
                    str2.remove(char2)
                    return lcs(''.join(str1), ''.join(str2), accs=accs)
        str1.remove(char1)
        return lcs(''.join(str1), ''.join(str2), accs)
                
    else:
        return accs

print(lcs('AGGTAB','GXTXAYB'))
print(lcs('ABCDGH','AEDFHR'))
打印语句返回

['A', 'G', 'T', 'B']
['A', 'G', 'T', 'B', 'A', 'D', 'H']
第一个print语句是正确的,但第二个语句包含第一个语句的子字符串

当我在上面代码下方的单元格中运行函数lcs(无参数)而不调用它时,我得到以下结果:

<function __main__.lcs(str1='', str2='', accs=['A', 'G', 'T', 'B', 'A', 'D', 'H', 'A', 'D', 'H'])>

我尝试在Jupyter实验室的单元格中运行代码,然后在VSCode和命令行中将其作为脚本运行,并且值似乎在这两者的参数中累积。这里发生了什么


在Windows上的WSL2和Python3.9.1下在Ubuntu中运行Python3.8.5。这两个地方的问题类似。

在下一次函数调用之前,应该为变量accs分配一个空列表。如果未清除该accs值,则第二个函数调用将第一个函数调用的accs值作为参数

print(lcs('AGGTAB','GXTXAYB'))
print(lcs('ABCDGH','AEDFHR', []))

@这是一个众所周知的常见陷阱,你也可以找到信息。此处-

这是否回答了您的问题?@Daniel Hao发布了一个很好的链接,您也可以在此处查找解释: