參考《python cookbook》
python 中的 collections 中的 most_common()
方法可以快速找到序列中出現(xiàn)元素的個數(shù)
#!/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']
# 統(tǒng)計出現(xiàn)次數(shù)最多的前三個元素
word_counts = Counter(words)
top_three = word_counts.most_common(3)
print(top_three) # [('eyes', 8), ('the', 5), ('look', 4)]
# 給出各元素出現(xiàn)次數(shù)
print(word_counts['not']) # 1
print(word_counts['look']) # 4
print(word_counts['eyes']) # 8
# # 對words 序列元素增加計數(shù)
# # 方法一
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
# 對序列元素數(shù)進行數(shù)學運算
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)