我希望递归地计算列表中的项目。例如,我列出了几个列表:
a = ['b', 'c', 'h']
b = ['d']
c = ['e', 'f']
h = []
我试图找到一种方法,在其中找出列表的长度' a'。但在列表中' a'我有''' c'并且' h' ...因此我的功能进入列表' b'并计算那里的元素数量......然后列出' c'然后最后列出' h'。
答案 0 :(得分:2)
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
答案 1 :(得分:-1)
最适合我的解决方案是:
def recur(arr):
if not arr:
return 0
else:
return 1 + recur(arr[1:])