How to count items in list recursively

泄露秘密 提交于 2021-01-29 17:58:06

问题


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'. 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'.


回答1:


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():

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



回答2:


The solution that worked for me was this:

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


来源:https://stackoverflow.com/questions/26455612/how-to-count-items-in-list-recursively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!