如何递归计算列表中的项目数

And*_*dre 1 python recursion list

我希望递归地计算列表中的项目。例如,我列出了几个列表:

a = ['b', 'c', 'h']
b = ['d']
c = ['e', 'f']
h = []
Run Code Online (Sandbox Code Playgroud)

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

Pad*_*ham 5

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
Run Code Online (Sandbox Code Playgroud)

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

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])
Run Code Online (Sandbox Code Playgroud)

如果您想获得更深层的嵌套列表,您可以展平并获得 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
Run Code Online (Sandbox Code Playgroud)