使用递归获取Python中列表的长度 [英] Get length of list in Python using recursion

查看:233
本文介绍了使用递归获取Python中列表的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试计算列表的长度.当我在cmd上运行它时,我得到:

I am trying to calculate the length of a list. When I run it on cmd, I get:


RuntimeError: maximum recursion depth exceeded in comparison

我认为我的代码没有任何问题:

I don't think there's anything wrong with my code:

def len_recursive(list):
    if list == []:
        return 0
    else:
        return 1 + len_recursive(list[1:])

推荐答案

Python中的递归深度是有限的,但是可以按照此尾调用优化,则此解决方案适用于任意长度的列表:

The recursion depth in Python is limited, but can be increased as shown in this post. If Python had support for the tail call optimization, this solution would work for arbitrary-length lists:

def len_recursive(lst):
    def loop(lst, acc):
        if not lst:
            return acc
        return loop(lst[1:], acc + 1)
    return loop(lst, 0)

但实际上,您将必须使用较短的列表和/或增加允许的最大递归深度.

But as it is, you will have to use shorter lists and/or increase the maximum recursion depth allowed.

当然,没有人会在现实生活中使用此实现(而是使用 len() 内置函数),我猜这是递归的学术示例,但是即使如此,最好的方法还是使用迭代,如@poke的答案所示.

Of course, no one would use this implementation in real life (instead using the len() built-in function), I'm guessing this is an academic example of recursion, but even so the best approach here would be to use iteration, as shown in @poke's answer.

这篇关于使用递归获取Python中列表的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆