python cookbook 1.12找出序列中出现次数最多的元素

#1.12找出序列中出现次数最多的元素
#collections模块中的Counter类正式这样的用法,most_common()可以直接统计
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
from collections import Counter
words_counts = Counter(words)    #统计所有元素以及出现的次数
print(words_counts)
top_tree = words_counts.most_common(3)   #统计出现次数最多的元素
print(top_tree)
print(words_counts['eyes'])   #查看某元素出现的次数

morewords =  ['why','are','you','not','looking','in','my','eyes']   #新的数据
for word in morewords:
    words_counts[word]+=1    #更新新数据
print(words_counts['eyes'])

words_counts.update(morewords)
print(words_counts)   #或者用这种方法,因为上面更新了一次,再更新相当于更新了两次

 

a = Counter(words)
b = Counter(morewords)
print(a)
print(b)
c=a+b   #将两个合起来
print(c)
d=a-b
print(d)   #从a中去除b

猜你喜欢

转载自blog.csdn.net/qq_21997625/article/details/86361456
今日推荐