如何递归统计列表中的项目数
我想要递归地计算一个列表中的项目数量。比如说,我有一个包含几个列表的列表:
a = ['b', 'c', 'h']
b = ['d']
c = ['e', 'f']
h = []
我在尝试找一种方法来计算列表'a'的长度。但是在列表'a'里面还有'b'、'c'和'h'这些列表……所以我的函数会先进入列表'b',然后计算里面的元素数量……接着是列表'c',最后是列表'h'。
2 个回答
1
对我有效的解决办法是这个:
def recur(arr):
if not arr:
return 0
else:
return 1 + recur(arr[1:])
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
添加了打印功能来帮助理解输出结果:
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()来计算长度:
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