小编典典

嵌套列表和count()

python

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

如果列表是:

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

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

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

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


阅读 286

收藏
2021-01-20

共1个答案

小编典典

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

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
2021-01-20