Python中的Counter对象

Counter对象(重点)

collections包下的Counter()方法用来统计迭代器中各个元素的次数,并生成一个字典,其中键代表元素,值代表出现的次数

另外如果通过Counter并不存在的key访问value,将会输出0,代表该key出现了0次

【例】力扣第1160题拼写单词:给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。注意:每次拼写(指拼写词汇表中的一个单词)时,chars 中的每个字母都只能用一次。返回词汇表 words 中你掌握的所有单词的 长度之和。

from collections import Counter
class Solution:
    def countCharacters(self, words: List[str], chars: str) -> int:
        cnt = 0
        dic_chars = Counter(chars)
        for w in words:
            dic_words = Counter(w)
            for key in dic_words:
                if dic_words[key] > dic_chars[key]:
                    break
            #如果遍历完了仍然没有break则执行else
            else:
                cnt += len(w)
        return cnt

        cnt = 0
        dic_chars = Counter(chars)
        for w in words:
            dic_words = Counter(w)
            for key in dic_words:
                if dic_words[key] > dic_chars[key]:
                    break
            else:
                cnt+=len(w)
        return cnt

1、Counter对象的初始化

#Counter对象初始化
from collections import Counter
c1 = Counter()
c2 = Counter(('good', 'day' ,'commander'))
print(c2)
c3 = Counter(['Python','Swift','Python','Python','Swift'])
print(c3)
c4 = Counter('Hello')
print(c4)
c5 = Counter({'red':4,'blue':2})
print(c5)
c6 = Counter(Python = 4,Swift = 8)
print(c6)

结果为

Counter({'good': 1, 'day': 1, 'commander': 1})
Counter({'Python': 3, 'Swift': 2})
Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})
Counter({'red': 4, 'blue': 2})
Counter({'Swift': 8, 'Python': 4})

2、Counter对象的常用方法
elements()方法返回Counter所包含的全部元素组成的迭代器
most_common(n)方法返回Counter中出现最多的n个元素

#Counter对象常用方法
from collections import Counter
cnt = Counter()
print(cnt['Python'])
for word in ['Swift','Python','Python','Kotlin']:
    cnt[word] += 1
print(cnt)
#只访问Counter对象的元素,相当于取出Counter中的所有key
print(list(cnt.elements()))
print(list(cnt.keys()))
#获取出现次数最多的字母
chr_cnt = Counter('abasdefqgsda')
print(chr_cnt.most_common(3))

结果为

0
Counter({'Python': 2, 'Swift': 1, 'Kotlin': 1})
['Swift', 'Python', 'Python', 'Kotlin']
['Swift', 'Python', 'Kotlin']
[('a', 3), ('s', 2), ('d', 2)]

【例】力扣第451题根据字符出现频率排序:给定一个字符串,请将字符串里的字符按照出现的频率降序排列。

from collections import Counter
class Solution:
    def frequencySort(self, s: str) -> str:
        c = Counter(s).most_common()
        return ''.join([i*j for i,j in c])

3、Counter对象的常见操作

#Counter对象的常用操作
from collections import Counter
c = Counter(['Python','Swift','Python','Python','Swift','Kotlin','Zhaochen'])
print(c)
print(sum(c.values()))
#将字典转化为列表则只保留key
print(list(c))
print(dict(c))
#获取c中出现次数最少的2个元素
print(c.most_common()[:-3:-1])
#加减交并等运算
x = Counter(a=1,b=1,c=-1)
y = Counter(a=1,b=-2,d=3)
print(x+y)
print(x-y)
print(x&y)
print(x|y)
print(+c)
print(-d)

结果为

Counter({'Python': 3, 'Swift': 2, 'Kotlin': 1, 'Zhaochen': 1})
7
['Python', 'Swift', 'Kotlin', 'Zhaochen']
{'Python': 3, 'Swift': 2, 'Kotlin': 1, 'Zhaochen': 1}
[('Zhaochen', 1), ('Kotlin', 1)]
Counter({'d': 3, 'a': 2})
Counter({'b': 3})
Counter({'a': 1})
Counter({'d': 3, 'a': 1, 'b': 1})
Counter({'Python': 3, 'Swift': 2, 'Kotlin': 1, 'Zhaochen': 1})
Counter()
发布了8 篇原创文章 · 获赞 0 · 访问量 8

猜你喜欢

转载自blog.csdn.net/weixin_42713642/article/details/105449062
今日推荐