繁体   English   中英

如何汇总列表数

[英]How to Sum up number of 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']]]

清单的总和是6

方法1

给我4

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

方法2

给我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

如何汇总列表数量?

您可以通过一些递归来做到这一点,正如您已经在其中一个函数中所示的那样

如果该项目是list并且该项目不包含任何list ,则该函数仅加1进行count 否则,将在该项目上再次递归调用该函数。

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

这是工作流程:

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