Python Counter的简单用法

这玩意是collections中的一个类,至于作用嘛,如字面意思,计数,统计每个元素的出现次数。一个例子如下:

from collections import Counter

lst = [1, 1, 1, 2, 3, 3]
cnt = Counter(lst)
print(type(cnt))
for key, value in cnt.items():
    print(key, value)
print(cnt[3])

输出结果如下:

<class 'collections.Counter'>
1 3
2 1
3 2
2

具体来说,调用Counter包装后得到的是一个Counter对象,这个对象可以直接按照hashmap的风格来访问。比方说,我们要求lst中数字3的出现次数,那么直接访问cnt[3]即可。

这么做有什么好处呢?如果使用hashmap来实现类似的功能的话,那么代码则是这样的:

cnt = dict()
for t in lst:
    if t not in cnt.keys():
        cnt[t] = 0
    cnt[t] += 1
print(type(cnt))
print(cnt.items())
for key, value in cnt.items():
    print(key, value)
print(cnt[3])

也就是省去了for循环把数据塞进hashmap的这一步。

例题:Leetcode 1512. 好数对的数目
解答:

class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:
        return sum([v * (v - 1) // 2 for k, v in collections.Counter(nums).items()])

猜你喜欢

转载自blog.csdn.net/qq_40714949/article/details/125814034