递归Python函数中的持久对象
我正在尝试编写一个递归函数,该函数需要在递归时存储和修改对象(例如集合)。我应该在函数内使用全局名称吗?另一种选择是修改或继承函数参数的类,以便它可以保留这个持久对象,但我觉得它不太优雅。如果我完全放弃递归,我也可以使用堆栈......
有没有一种Pythonic方法可以做到这一点?发电机可以解决这个问题吗?
I am trying to write a recursive function that needs to store and modify an object (say a set) as it recurses. Should I use a global name inside the function? Another option is to modify or inherit the class of the parameter of the function so that it can keep this persistent object but I don't find it elegant. I could also use a stack if I would forgo the recursion altogether...
Is there a pythonic way of doing this? Could a generator do the trick?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
只需通过递归方法传递持久对象即可。
Just pass through your persistent object through the recursive method.
对象通过引用传递。如果您只修改一个对象,则可以在递归函数中执行此操作,并且更改将全局可见。
如果您需要在递归函数内分配变量并在函数返回后查看它,那么您不能只使用
=
分配局部变量。您可以做的是更新另一个对象的字段。Objects are passed by reference. If you're only modifying an object, you can do that from within a recursive function and the change will be globally visible.
If you need to assign a variable inside a recursive function and see it after the function returns, then you can't just assign a local variable with
=
. What you can do is update a field of another object.将集合作为参数传递到递归方法中,然后在将其传递到下一步之前对其进行修改。复杂对象通过引用传递。
Pass the set into the recursive method as an argument, then modify it there before passing it to the next step. Complex objects are passed by reference.
如果它是一个容器(不是不可变的数据类型),您可以通过以下方式传递对象:(
不要问我那是什么意思......我只是输入随机的东西:P)
If it's a container (not an immutable data type), you can pass the object through:
(Don't ask me what that's meant to do... I was just typing random things :P)
如果您传递的对象是可变的,那么在较深的递归中对其进行的更改将在较早的递归中看到。
If the object you pass is mutable then changes to it in deeper recursions will be seen in earlier recursions.
使用函数的全局变量。
将对象作为累加器传递:
Use a variable global to the function.
Pass the object around as an accumulator: