利用python Counter找序列元素個(gè)數(shù)及計(jì)算

參考《python cookbook》

python 中的 collections 中的 most_common() 方法可以快速找到序列中出現(xiàn)元素的個(gè)數(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)計(jì)出現(xiàn)次數(shù)最多的前三個(gè)元素
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 序列元素增加計(jì)數(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
# 對序列元素?cái)?shù)進(jìn)行數(shù)學(xué)運(yùn)算
a = Counter(words)
b = Counter(morewords)
# a+b 將 words more_words 各相同元素進(jìn)行相加
c = a + b
print(c)
# a+b 將 words more_words 各相同元素進(jìn)行相減
d = a - b
print(d)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容