[英]python: recurcive list processing changes original list
What I'm trying to do is recursively process a list. 我正在尝试做的是递归处理列表。 I'm new to python so when all the code was written and sent to be executed I faced a strange problem: the list returns changed after calling the recursive function. 我是python的新手,所以当所有代码都被编写并发送执行时,我遇到了一个奇怪的问题:在调用递归函数后,列表返回了更改。 To test this I wrote that: 为了测试这个,我写道:
def recur(n):
n.append(len(n))
print '>',n
if n[-1]<5: recur(n)
print '<',n
And called the function: 并称为功能:
recur([])
Here was the result: 结果如下:
> [0]
> [0, 1]
> [0, 1, 2]
> [0, 1, 2, 3]
> [0, 1, 2, 3, 4]
> [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4, 5]
What I expected to see was 我期望看到的是
> [0]
> [0, 1]
> [0, 1, 2]
> [0, 1, 2, 3]
> [0, 1, 2, 3, 4]
> [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4, 5]
< [0, 1, 2, 3, 4]
< [0, 1, 2, 3]
< [0, 1, 2]
< [0, 1]
< [0]
, as it is for simple integer variables: ,因为它是简单的整数变量:
def recur(n):
n=n+1
print '>',n
if n<5: recur(n)
print '<',n
recur(0)
> 1
> 2
> 3
> 4
> 5
< 5
< 4
< 3
< 2
< 1
How can I fix the situation and what have I understood wrong? 我怎样才能解决这个问题以及我理解错误的原因?
All the recursive invocations of your function operate on the same list. 函数的所有递归调用都在同一个列表中运行。 You need to make a copy: 你需要复制一份:
def recur(n):
n.append(len(n))
print '>',n
if n[-1]<5: recur(n[:]) # <<<< Note the [:]
print '<',n
There are some good explanations in the answers to How do I pass a variable by reference? 在如何通过引用传递变量的答案中有一些很好的解释?
As the other answers indicated, you are mutating the list in place. 正如其他答案所示,您正在改变列表。 You could make copies of the list and/or use an immutable data structure, like a tuple: 您可以制作列表的副本和/或使用不可变的数据结构,如元组:
def recur(n=()):
if len(n) > 4:
return n
return recur(n + (len(n),))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.