日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

《Python Cookbook 3rd》笔记(1.12):序列中出现次数最多的元素

發(fā)布時間:2023/12/13 python 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 《Python Cookbook 3rd》笔记(1.12):序列中出现次数最多的元素 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

序列中出現(xiàn)次數(shù)最多的元素

問題

怎樣找出一個序列中出現(xiàn)次數(shù)最多的元素呢?

解法

collections.Counter 類就是專門為這類問題而設(shè)計的,它甚至有一個有用的most_common() 方法直接給了你答案。
為了演示,先假設(shè)你有一個單詞列表并且想找出哪個單詞出現(xiàn)頻率最高。你可以這
樣做:

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 word_counts = Counter(words) # 出現(xiàn)頻率最高的 3 個單詞 top_three = word_counts.most_common(3) print(top_three) # Outputs [('eyes', 8), ('the', 5), ('look', 4)]

討論

作為輸入, Counter 對象可以接受任意的 hashable 序列對象。在底層實現(xiàn)上,一個 Counter 對象就是一個字典,將元素映射到它出現(xiàn)的次數(shù)上。比如:

>>> word_counts['not'] 1 >>> word_counts['eyes'] 8 >>>

如果你想手動增加計數(shù),可以簡單的用加法:

>>> morewords = ['why','are','you','not','looking','in','my','eyes'] >>> for word in morewords: ... word_counts[word] += 1 ... >>> word_counts['eyes'] 9 >>>

或者你可以使用 update() 方法:

>>> word_counts.update(morewords) >>>

Counter 實例一個鮮為人知的特性是它們可以很容易的跟數(shù)學(xué)運算操作相結(jié)合。比如:

>>> a = Counter(words) >>> b = Counter(morewords) >>> a Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2, "you're": 1, "don't": 1, 'under': 1, 'not': 1}) >>> b Counter({'eyes': 1, 'looking': 1, 'are': 1, 'in': 1, 'not': 1, 'you': 1, 'my': 1, 'why': 1}) >>> # Combine counts >>> c = a + b >>> c Counter({'eyes': 9, 'the': 5, 'look': 4, 'my': 4, 'into': 3, 'not': 2, 'around': 2, "you're": 1, "don't": 1, 'in': 1, 'why': 1, 'looking': 1, 'are': 1, 'under': 1, 'you': 1}) >>> # Subtract counts >>> d = a - b >>> d Counter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2, "you're": 1, "don't": 1, 'under': 1}) >>>

毫無疑問, Counter 對象在幾乎所有需要制表或者計數(shù)數(shù)據(jù)的場合是非常有用的工具。在解決這類問題的時候你應(yīng)該優(yōu)先選擇它,而不是手動的利用字典去實現(xiàn)。

總結(jié)

以上是生活随笔為你收集整理的《Python Cookbook 3rd》笔记(1.12):序列中出现次数最多的元素的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。