[英]Python: How to sort a list of lists by the most common first element?
[英]How to get the most common element from a list in python
我有一個如此處所示的列表。 a=[1936,2401,2916,4761,9216,9216,9604,9801]
我想得到更多重復的值。 在這里它是'9216'我怎么能得到這個值? 謝謝
https://docs.python.org/2.7/library/collections.html#counter
來自收藏夾進口櫃台櫃台(a).most_common(1)
這是另一個不使用計數器的人
a=[1936,2401,2916,4761,9216,9216,9604,9801]
frequency = {}
for element in a:
frequency[element] = frequency.get(element, 0) + 1
# create a list of keys and sort the list
# all words are lower case already
keyList = frequency.keys()
keyList.sort()
print "Frequency of each word in the word list (sorted):"
for keyElement in keyList:
print "%-10s %d" % (keyElement, frequency[keyElement])
有兩種標准庫方法可以做到這一點:
from statistics import mode
most_common = mode([3, 2, 2, 2, 1]) # 2
most_common = mode([3, 2]) # StatisticsError: no unique mode
collections.Counter.most_common
:
from collections import Counter
most_common, count = Counter([3, 2, 2, 2, 1]).most_common(1)[0] # 2, 3
most_common, count = Counter([3, 2]).most_common(1)[0] # 3, 1
兩者在性能方面都是相同的,但是當沒有唯一的最常見元素時,第一個引發異常,第二個也返回頻率。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.