繁体   English   中英

如何计算列表中特定类型的出现次数?

[英]How to count occurrences of specific type in a list?

有没有一种简单的方法来计算列表中有多少特定类型的元素?

这就是我的想法和我尝试过的。

ex_list = ["string", "data", "item", 1, 3, {3: "im dict"}, "im_item"]

print(ex_list.count(int)) # -> 0, should return 2
print(ex_list.count(type(str))) # -> 0, should return 4

我知道有一些解决方法(使用循环等),但我想知道是否有像只使用一个函数(如计数函数等)一样简单的东西。

import operator
operator.countOf(map(type, ex_list), int)

在线试试吧!

文档

您可以使用Counter类(来自collections )与类型的映射:

from collections import Counter

ex_list = ["string", "data", "item", 1, 3, {3: "im dict"}, "im_item"]

typeCounts = Counter(map(type,ex_list))
>>> typeCounts
Counter({<class 'str'>: 4, <class 'int'>: 2, <class 'dict'>: 1})
>>> typeCounts[int]
2

这将在 O(n) 时间内进行初始计数,此后每次使用typeCounts[type]都将是 O(1)。

我不会将循环称为解决方法; 对此的任何解决方案都将使用循环,无论它是用 Python 编写的还是在后台编写的。 所以,这是一个使用isinstance()的循环解决方案,它允许子类。

def type_count(iterable, type_):
    return sum(isinstance(x, type_) for x in iterable)
>>> type_count(ex_list, int)
2
>>> type_count(ex_list, str)
4

如果您想使用Counter解决方案但允许子类,您可以通过每种类型的方法解析顺序(MRO),如下所示:

from collections import Counter

typeCounts = Counter(map(type, ex_list))
for t, n in list(typeCounts.items()):  # list() since the dict will change size
    for parent in t.__mro__[1:]:
        typeCounts[parent] += n
>>> typeCounts[int]
2
>>> typeCounts[object] == len(ex_list)
True

文档: class.__mro__

暂无
暂无

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

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