递归地计算列表的长度 [英] calculate length of list recursively

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

问题描述

如果你有一个list = [1,2,3,4,5]



你将如何递归计算该列表的长度而不使用len(list )?

  myarray = [1,2,3,4,5] 

def mylist( myarray):
if(myarray == []):
print(列表为空)
返回
返回1 +?

不希望使用len,但每次在列表中存在值时只加1。

def list_length(L):
... if L:
... return 1 + list_length(L [1:])
... return 0
...
>>> list_length(myarray)
5
>>> list_length([])
0
>>> list_length([1] * 4)
4
>>>

如果列表包含元素,则返回1 +列表的长度减一个元素。



你可以通过几种不同的方式来做到这一点,但切片[:1]或[1:]会分别减去最后或第一个元素,这是合理的。 >

如果列表中没有元素,则返回0


If you have a list = [1,2,3,4,5]

how would you recursively calculate the length of that list without using len(list)?

myarray = [1,2,3,4,5]

def mylist(myarray):
    if (myarray == []):
        print ("The list is empty")
        return 
    return 1 + ?

Don't want to use len but just add 1 each time there exists a value in list. How would I do that?

解决方案

>>> def list_length(L):
...     if L:
...         return 1 + list_length(L[1:])
...     return 0
... 
>>> list_length(myarray)
5
>>> list_length([])
0
>>> list_length([1]*4)
4
>>> 

If the list has elements, return 1 + the length of the list minus one element.

You can do this a couple different ways, but slicing [:1] or [1:] will give you the elements minus the last or first respectively, makes sense.

If the list has no elements, return 0

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

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