Python每日一練0009

問題

怎樣找出一個序列中出現次數最多的元素?

解決方案

使用collections庫中的Counter對象可以方便的求出現次數最多的前N個元素

直接使用most_common成員函數就好了,例如:

from collections import Counterwords = [ look, into, my, eyes, look, into, my, eyes, the, eyes, the, eyes, the, eyes, not, around, the, eyes, "dont", look, around, the, eyes, look, into, my, eyes, "youre", under]counter = Counter(words)print(counter.most_common(1))

輸出

[(eyes, 8)]

討論

Counter對象是dict的子類,事實上內部存儲也是按照k-v字典存儲的,這裡的v就是次數,所以Counter對象支持dict對象的所有操作

每一個Counter對象初始化可以接受可迭代對象(iterable)、字典、關鍵字參數

>>> c = Counter() # a new, empty counter>>> c = Counter(gallahad) # a new counter from an iterable>>> c = Counter({red: 4, blue: 2}) # a new counter from a mapping>>> c = Counter(cats=4, dogs=8) # a new counter from keyword args

此外,Counter對象還支持數學操作

>>> c = Counter(a=3, b=1)>>> d = Counter(a=1, b=2)>>> c + d # add two counters together: c[x] + d[x]Counter({a: 4, b: 3})>>> c - d # subtract (keeping only positive counts)Counter({a: 2})>>> c & d # intersection: min(c[x], d[x]) Counter({a: 1, b: 1})>>> c | d # union: max(c[x], d[x])Counter({a: 3, b: 2})

所以在遇到跟計數有關的問題時,不妨首先考慮一下Counter對象

來源

Python Cookbook

關注

歡迎關注我的微信公眾號:python每日一練

weixin.qq.com/r/YygOFnn (二維碼自動識別)

推薦閱讀:

動態類型的語言的優缺點有哪些?
flowpy語法特性總覽和二進位包
Python為什麼代碼縮進不同,輸出結果不同?
Python3《機器學習實戰》學習筆記(九):支持向量機實戰篇之再撕非線性SVM
Loan Company Data Analysis

TAG:Python | Python入門 | Python3x |