嵌套列表和count()

发布于 2021-01-29 14:10:29

我想获取x在嵌套列表中出现的次数。

如果列表是:

list = [1, 2, 1, 1, 4]
list.count(1)
>>3

还行吧。但是如果列表是:

list = [[1, 2, 3],[1, 1, 1]]

如何获得1出现的次数?在这种情况下,4。

关注者
0
被浏览
117
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    这是扁平化嵌套序列的另一种方法。将序列展平后,可以很容易地进行检查以找到项目数。

    def flatten(seq, container=None):
        if container is None:
            container = []
    
        for s in seq:
            try:
                iter(s)  # check if it's iterable
            except TypeError:
                container.append(s)
            else:
                flatten(s, container)
    
        return container
    
    
    c = flatten([(1,2),(3,4),(5,[6,7,['a','b']]),['c','d',('e',['f','g','h'])]])
    print(c)
    print(c.count('g'))
    
    d = flatten([[[1,(1,),((1,(1,))), [1,[1,[1,[1]]]], 1, [1, [1, (1,)]]]]])
    print(d)
    print(d.count(1))
    

    上面的代码打印:

    [1, 2, 3, 4, 5, 6, 7, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
    1
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
    12
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看