問題:求以下序列元素出現(xiàn)次數(shù)前三的元素
import collections
words = [
'look', 'into', 'my', 'look', 'into', 'my', 'eyes',
'look', 'into', 'my', 'look', 'into', 'my', 'eyes', 'the', 'not',
'my', 'my', 'look'
]
words_counts = collections.Counter(words) # 在底層中,Counter是一個(gè)字典,在元素和它們出現(xiàn)的次數(shù)間做了映射
top_three = words_counts.most_common(3) # 返回出現(xiàn)次數(shù)前三的元素
top_three
Out[4]: [('my', 6), ('look', 5), ('into', 4)]
# 可以給Counter對(duì)象提供任何可哈希的對(duì)象序列作為輸入歧蒋,在底層中差油,Counter是一個(gè)字典烁登,在元素和它們出現(xiàn)的次數(shù)間做了映射
words_counts['my']
Out[5]: 6
words_counts['eyes']
Out[6]: 2
Counter對(duì)象操作的使用示例
# 1蝙斜、實(shí)現(xiàn)簡(jiǎn)單的元素自增計(jì)數(shù)
morewords = ['why', 'are', 'you', 'not', 'looking', 'in', 'my', 'eyes']
for word in morewords:
words_counts[word] += 1
words_counts['my']
Out[7]: 7
# 2、使用update()方法
words_counts.update(morewords) # update()方法更改元素字典映射
words_counts.most_common(1)
Out[8]: [('my', 8)]
# 3续捂、Counter對(duì)象可以同各種數(shù)學(xué)運(yùn)算操作結(jié)合起來使用
a = collections.Counter(words)
b = collections.Counter(morewords)
a
Out[10]: Counter({'eyes': 2, 'into': 4, 'look': 5, 'my': 6, 'not': 1, 'the': 1})
b
Out[11]:
Counter({'are': 1,
'eyes': 1,
'in': 1,
'looking': 1,
'my': 1,
'not': 1,
'why': 1,
'you': 1})
a+b
Out[12]:
Counter({'are': 1,
'eyes': 3,
'in': 1,
'into': 4,
'look': 5,
'looking': 1,
'my': 7,
'not': 2,
'the': 1,
'why': 1,
'you': 1})
a-b
Out[13]: Counter({'eyes': 1, 'into': 4, 'look': 5, 'my': 5, 'the': 1})