参考《python cookbook》
python 中的 collections 中的 most_common()
方法可以快速找到序列中出现元素的个数
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2024/8/1 下午9:37
# @Author : s
from collections import Counter
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']
# 统计出现次数最多的前三个元素
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three) # [('eyes', 8), ('the', 5), ('look', 4)]
# 给出各元素出现次数
print(word_counts['not']) # 1
print(word_counts['look']) # 4
print(word_counts['eyes']) # 8
# # 对words 序列元素增加计数
# # 方法一
morewords = ['why', 'are', 'you', 'not', 'looking', 'in', 'my', 'eyes']
for word in morewords:
word_counts[word] += 1
print(word_counts['eyes']) # 9
# 方法二
word_counts.update(morewords)
print(word_counts['eyes']) # 9
# 对序列元素数进行数学运算
a = Counter(words)
b = Counter(morewords)
# a+b 将 words more_words 各相同元素进行相加
c = a + b
print(c)
# a+b 将 words more_words 各相同元素进行相减
d = a - b
print(d)