为什么我的 python 函数返回多个括号?
我对 python 有点菜鸟,但我正在尝试创建一个递归函数,它的工作方式就像内置的 range 函数:
def Range (lo, hi):
if lo >= hi:
return []
else:
return [lo, Range (lo+1,hi)]
但它返回多个列表。
它返回的是 [3,[4,[5,[6,[]]]]][3,4,5,6]
代码> 这是为什么?我该如何解决?
I'm somewhat of a noob to python but I'm trying to create a recursive function which works just like the built in range function:
def Range (lo, hi):
if lo >= hi:
return []
else:
return [lo, Range (lo+1,hi)]
but its returning multiple lists.
Instead of [3,4,5,6]
, which is what I want, its returning [3,[4,[5,[6,[]]]]]
Why is this and how do I fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当你像这样递归时,
Range
每次都会返回一个列表:为了避免这种情况,请将列表添加在一起:
编辑:
正如@delnan指出的,这个函数是< em>非常效率低下 - 它在没有尾部调用优化的语言中递归*并且它生成两个(可能三个)每个递归级别的新列表。 @mipadi 的答案性能更高,因为它只创建一个列表(
acc
或accumulator
参数)并在递归时传递它。* 这可能对于 Python 语言来说并不正确,但我 99% 确信对于最常见的 Python 实现(即 CPython)来说这是正确的。
When you recurse like that,
Range
returns a list each time:In order to avoid this, add your lists together:
EDIT:
As @delnan points out, this function is very inefficient - it both recurses in a language without tail-call optimization* and it generates two (possibly three) new lists for each level of recursion. @mipadi's answer is more performant because it creates only one list (the
acc
oraccumulator
argument) and passes it as it recurses.* This may not be true for the Python language, but I'm 99% sure it is true for the most common implementation of Python, namely CPython.
您的
Range
函数返回一个列表,因此在最后一行中您将返回列表中的列表。您可能应该做的是维护一个累加器并向其添加值:Your
Range
function returns a list, so in your last line you are returning a list within a list. What you probably should do is maintain an accumulator and add values to that:但你可能会得到 StackOverflow
but you might get StackOverflow
Range 中的每次递归都会返回一个列表,它是上一次递归的列表中的第二个元素。当然 Python 有一个内置函数,但是如果你想自己构建它,你可能只想以
Each recursion into Range returns a list, which is the second element in the list for the previous recursion. Of course Python has a built-in function for this, but if you want to build it yourself, you probably just want to end with