[英]How can i define a shared list in the recursive function in python?
I want to encapsulate my function and define the list in the function, not before it: for example in this code:我想封装我的 function 并在 function 中定义列表,而不是在它之前:例如在此代码中:
s = []
def rec(n):
if n == 0:
return s
else:
s.append(n)
rec(n-1)
return s
print(rec(5))
but when i define it in the recursive function, it become local.但是当我在递归 function 中定义它时,它就变成了本地的。
You can do this by pass the list (with a default value) in your recursive function's argument:您可以通过在递归函数的参数中传递列表(带有默认值)来做到这一点:
def rec(n, s=[]):
if n == 0:
return s
else:
s.append(n)
rec(n-1, s)
return s
print(rec(5))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.