简体   繁体   English

如何汇总列表数

[英]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 清单的总和是6

Approach 1 方法1

Gives me 4 给我4

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

Approach 2 方法2

Gives me 8 给我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. 如果该项目是list并且该项目不包含任何list ,则该函数仅加1进行count 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

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

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