如何递归计数列表中的项目 [英] How to count items in list recursively

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

问题描述

我希望递归地计算列表中的项目.例如,我列出了一些列表:

I am looking to count the items in a list recursively. For example, I have a list few lists:

a = ['b', 'c', 'h']
b = ['d']
c = ['e', 'f']
h = []

我试图找到一种方法来找出列表'a'的长度.但是在列表'a'中我有'b','c'和'h'...因此我的函数进入列表'b'并计算那里的元素数量...然后列出'c'然后最后列出"h".

I was trying to find a way in which I find out the length of list 'a'. But in list 'a' I have 'b', 'c' and 'h' ... hence my function then goes into list 'b' and counts the number of elements there... Then list 'c' and then finally list 'h'.

推荐答案

b = ['d']
c = ['e', 'f']
h = []
a = [b,c,h]

def recur(l):
    if not l: # keep going until list is empty
        return 0
    else:
        return recur(l[1:]) + len(l[0]) # add length of list element 0 and move to next element

In [8]: recur(a)
Out[8]: 3

添加了打印以帮助理解输出:

Added print to help understand the output:

def recur(l,call=1):
    if not l:
        return 0
    else:
        print("l = {} and  l[0] = {} on recursive call {}".format(l,l[0],call))
        call+=1
        return recur(l[1:],call) + len(l[0])

如果要获得更深层的嵌套列表,可以展平并获得len():

If you want to get more deeply nested lists you can flatten and get the len():

b = ['d']
c = ['e', 'f',['x', 'y'],["x"]]
h = []
a = [b,c,h]
from collections import Iterable

def flatten_nest(l):
    if not l:
        return l
    if isinstance(l[0], Iterable) and not isinstance(l[0],basestring): # isinstance(l[0],str) <- python 3
        return flatten_nest(l[0]) + flatten_nest(l[1:])
    return l[:1] + flatten_nest(l[1:])


In [13]: len(flatten_nest(a))
Out[13]: 6

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

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