嵌套列表和 count() [英] Nested List and count()

查看:32
本文介绍了嵌套列表和 count()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to get the number of times x appears in the nested list.

如果列表是:

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

没问题.但是如果列表是:

This is OK. But if the list is:

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

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

How can I get the number of times 1 appears? In this case, 4.

推荐答案

这里是另一种展平嵌套序列的方法.一旦序列变平,就可以轻松检查项目数.

Here is yet another approach to flatten a nested sequence. Once the sequence is flattened it is an easy check to find count of items.

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

这篇关于嵌套列表和 count()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆