简体   繁体   中英

How to Sum up number of list

I want to sum up a total number of list from a nested list.

datalist = [['a', 'b', 'c', 'a'], [['b', 'd', 'a', 'c'], ['a', 'a', 'a', 'b']], ['a', 'b', 'g', 'h'], [['x', 'z', 'c', 'c'], ['b', 'c', 'b', 'a']]]

Sum of list is 6

Approach 1

Gives me 4

print sum(1 for x in datalist if isinstance(x, list))
# 4

Approach 2

Gives me 8

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

print count_list(datalist)
#8

How can I sum up the number of list?

You may be able to do this with some recursion, as you've already shown in one of your functions

The function only adds 1 to count if the item is a list and the item does not contain any lists. Else, the function is called on the item again, recursively.

datalist = [['a', 'b', 'c', 'a'], [['b', 'd', 'a', 'c'], ['a', 'a', 'a', 'b']], ['a', 'b', 'g', 'h'], [['x', 'z', 'c', 'c'], ['b', 'c', 'b', 'a']]]

def count_nested_lists(lst):
    count = 0
    for item in lst:
        if isinstance(item, list):
            if not any(isinstance(l, list) for l in item):
                count += 1
            else:
                count += count_nested_lists(item)
    return count

print(count_nested_lists(datalist))
# 6

Here is the working flow :

>>> def count(local_list):
...     sum1 = 0
...     for l in local_list:
...             if not isinstance(l,list):
...                     return 1 
...             else:
...                     sum1+= count(l) 
...     
...     return sum1
... 
>>> count([['a', 'b', 'c', 'a'], [['b', 'd', 'a', 'c'], ['a', 'a', 'a', 'b']], ['a', 'b', 'g', 'h'], [['x', 'z', 'c', 'c'], ['b', 'c', 'b', 'a']]])
6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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