简体   繁体   English

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

[英]How to count items in list recursively

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 = []

I was trying to find a way in which I find out the length of list 'a'.我试图找到一种方法来找出列表“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'.但是在列表“a”中,我有“b”、“c”和“h”......因此我的函数然后进入列表“b”并计算那里的元素数量......然后列出“c”,然后最后列出'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])

If you want to get more deeply nested lists you can flatten and get the len():如果您想获得更深的嵌套列表,您可以展平并获得 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

The solution that worked for me was this:对我有用的解决方案是这样的:

def recur(arr):
 if not arr:
  return 0
 else:
  return 1 + recur(arr[1:])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM