Count the number of lists with recursion?

Here is what I tried:

def recursive_list_counter(l):
    sum = 0
    for e in l:
        if type(e) == type([]):
            #print e
            sum += 1
            recursive_list_counter(e)
    return sum 

# should be 6 if I count the first also
recursive_list_counter([[[13, 7], 90], 2, [1, 100, [5, [2]]], 8, 6])

I want to use recursion to retrieve the number of lists in a list, also counting the original list.

+4
source share
6 answers

Your recursive call ignores what is returned. Add the return value:

def recursive_list_counter(l):
    sum = 0
    for e in l:
        if isinstance(e, list):
            sum += 1
            sum += recursive_list_counter(e)
    return sum 

Note that the external list is ignored in the counter, so the call returns 5, not 6.

In addition, you should use isinstance()to check whether an object is of a given type.

If you want to see 6, count the current list in a function and leave the count of nested lists to recursive calls:

def recursive_list_counter(l):
    sum = 1
    for e in l:
        if isinstance(e, list):
            sum += recursive_list_counter(e)
    return sum 
+10
source

, , , , [

>>> li = [[[13, 7], 90], 2, [1, 100, [5, [2]]], 8, 6]
>>> str(li).count('[') 
6
+8

, . , , 3 .: P

#!/usr/bin/env python

def lcount(l):
    count = 0 
    if isinstance(l, list):
        count+=1
        count+=sum([lcount(x) for x in l]) 

    return count


list_ = [ [ [1, 2, 3], [1, 4, 5], [7, 8, 9]], [ 1, 2, 7], 1, 3, ]
print lcount(list_)
+3

:

def recursive_list_counter(li):
  return 1 + sum(map(recursive_list_counter, li)) if isinstance(li, list) else 0

, :

def recursive_element_counter(li):
  return sum(map(recursive_element_counter, li)) if isinstance(li, list) else 1
+3

:

  • isinstance,
  • sum ,
  • (: not isinstance(l, list))

:

def recursive_list_counter(l):
    if not isinstance(l, list):
        return 0
    return 1 + sum(recursive_list_counter(e) for e in l)
+3

. , recursive_list_counter, sum , .

sum = 0
def recursive_list_counter(l):
    global sum
    for e in l:
        if type(e) is list: #this is the same, but a better practice.
            #print e
            sum += 1
            recursive_list_counter(e)
    return sum 

recursive_list_counter([[[13, 7], 90], 2, [1, 100, [5, [2]]], 8, 6]) #returns 5

:

if type(e) is list:
    sum += 1
    sum += recursive_list_counter(e)

, !

+2

All Articles