天天看點

[00012] 序列中出現次數最多的元素序列中出現次數最多的元素

序列中出現次數最多的元素

一、 解決問題

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

二、解決方案

類:collections.Counter

方法: most_common()

三、代碼說明

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'
]

#生成Counter對象
word_counts = Counter(words)

#出現次數前三的元素
top_three = word_counts.most_common()
print (top_three)
"""
傳回結果:[('eyes', 8), ('the', 5), ('look', 4)]
"""
           
說明:使用Counter類下的most_common(n) 方法可以傳回一個清單, 如果n為None的話,則顯示是以的(key,value)形式的值, key->words中的值,value->出現的次數。

四、關聯知識

  1. Counter 類

    Counter類的目的是用來跟蹤值出現的次數。它是一個無序的容器類型,以字典的鍵值對形式存儲,其中元素作為key,其計數作為value。計數值可以是任意的Interger(包括0和負數)。Counter類和其他語言的bags或multisets很相似。

1.1 建立

c = Counter() # 建立空Counter類
print (c)
c = Counter("gallahad") # 從一個可iterable對象中建立(list, dict, str, set, tuple) 
print (c)
c = Counter({"a":, "b":}) #從一個字典中建立
c = Counter(a = , b = ) # 從一個字典解析中建立
           

1.2 計數值的房屋與缺失的鍵

#當所通路的鍵不存在時,傳回0,而不是KeyError;否則傳回它的計數。
c = Counter("abcdefgab")
print (c["a"]) # -> 2
print (c["h"]) # -> 0
           

1.3 計數器的更新(update和subtract)+/-

#新增
c = Counter('which')  
c.update('witch')  # 接受一個可iterable對象
print (c['h']) # ->3
d = Counter("watch")
c.update(d) # 接受另一個Counter對象
print(c['h']) # ->4
           
#減少 
c = Counter("which")
c.subtract("witch") #接受一個可iterable對象
print (c["h"]) # ->1
d = Counter("watch")
c.subtract(d)
print (c['a']) # ->-1
           

1.4 鍵的删除

#當計數值為時,并不意味着元素被删除,删除元素應當使用del。
c = Counter("abcdcba")
c["b"] = 
print (c) #Counter({'c': , 'a': , 'd': , 'b': })
del c["a"]
print (c) #Counter({'c': , 'd': , 'b': })
           

1.5 elements() 值

#傳回一個疊代器。元素被重複了多少次,在該疊代器中就包含多少個該元素。
#所有元素按照字母序排序,個數小于1的元素不被包含。
c = Counter(a = , b =, c = , d = -)
for i in c.elements():
    print(i, end=' ') # ->a a a a b b 
print()
           

1.6 most_common([n])

#傳回一個TopN清單。如果n沒有被指定,則傳回所有元素。當多個元素計數值相同時,按照字母序排列。
c = Counter("abracadabra")
print (c.most_common()) #->[('a', ), ('r', ), ('b', ), ('d', ), ('c', )]
print (c.most_common())#->[('a', ), ('b', ), ('r', )]
           

1.7 淺拷貝

c = Counter("abcdcba")
print (id(c)) #-> 18681432
Counter({'a': , 'c': , 'b': , 'd': })
d = c.copy()
print (id(d)) #-> 18680472
print (d == c) #-> True
           

1.8 算術和集合操作

#+、-、&、|操作也可以用于Counter。其中&和|操作分别傳回兩個Counter對象各元素的最小值和最大值。
#需要注意的是,得到的Counter對象将删除小于1的元素。

c = Counter(a=, b=)
d = Counter(a=, b=)
print (c + d) #-> Counter({'a': 4, 'b': 3})
print (c - d) #-> Counter({'a': 2})
print (c & d) #交集: min(c[x], d[x]) -> Counter({'a': , 'b': })
print (c | d) #并集: max(c[x], d[x]) -> Counter({'a': , 'b': })
           

1.9 常用操作

c = Counter('abracadabra')
print (sum(c.values())) #所有計數的總數 -> 
c.clear() # 重置Counter對象,注意不是删除
print (c) #-> Counter()

c = Counter('abracadabra')
print(list(c))# 将c中的鍵轉為清單 -> ['r', 'd', 'c', 'a', 'b']

print(set(c)) # 将c中的鍵轉為set -> {'b', 'r', 'c', 'd', 'a'}

print(dict(c))# 将c中的鍵值對轉為字典 ->{'r': , 'c': , 'a': , 'd': , 'b': }

print(c.items())  # 轉為(elem, cnt)格式的清單->dict_items([('c', ), ('b', ), ('r', ), ('d', ), ('a', )])

print(c.most_common()[::-]) #  取出計數最少的個元素 ->[('c', ), ('d', )]

c['a'] = -
print (c) #->Counter({'r': , 'b': , 'c': , 'd': , 'a': -})
c += Counter() #  移除和負值
print (c) #->Counter({'b': , 'r': , 'c': , 'd': })
           

五、總結

1.Counter 底層維護了一個dict執行個體,key儲存元素,value儲存出現次數;

六、代碼位址

github位址:https://github.com/weichen666/python_cookbook

目錄/檔案:first_selection/learn_collections_counter.py

七、參考

Python官網:https://docs.python.org/3.5/library/collections.html

pythoner網站: http://www.pythoner.com/