Python: Get most frequent item in list

怎甘沉沦 提交于 2020-01-02 08:47:10

问题


I've got a list of tuples, and I want to get the most frequently occurring tuple BUT if there are "joint winners" it should pick between them at random.

tups = [ (1,2), (3,4), (5,6), (1,2), (3,4) ]

so I want something that would return either (1,2) or (3,4) at random for the above list


回答1:


You can first use Counter to find the most repeated tuple. Then find the required tuples and finally randomize and get the first value.

from collections import Counter
import random

tups = [ (1,2), (3,4), (5,6), (1,2), (3,4) ]
lst = Counter(tups).most_common()
highest_count = max([i[1] for i in lst])
values = [i[0] for i in lst if i[1] == highest_count]
random.shuffle(values)
print values[0]



回答2:


Use collections.Counter:

>>> collections.Counter([ (1,2), (3,4), (5,6), (1,2), (3,4) ]).most_common()[0]
((1, 2), 2)

This is O(n log(n)).




回答3:


You can first sort the list to get the tuples sorted by frequency. After that a linear scan can get you the most frequent tuple from the list. Overall time O(nlogn)

>>> tups = [ (1,2), (3,4), (5,6), (1,2), (3,4) ]
>>> 
>>> sorted(tups)
[(1, 2), (1, 2), (3, 4), (3, 4), (5, 6)]



回答4:


This one should do your task in o(n) time:

>>> from random import shuffle
>>> from collections import Counter
>>>
>>> tups = [(1,2), (3,4), (5,6), (1,2), (3,4)]
>>> c = Counter(tups)                            # count frequencies
>>> m = max(v for _, v in c.iteritems())         # get max frq
>>> r = [k for k, v in c.iteritems() if v == m]  # all items with highest frq
>>> shuffle(r)                                   # if you really need random - shuffle
>>> print r[0]
(3, 4)



回答5:


Counting with collections.Counter and then random choice of the most common:

import collections
import random

lis = [ (1,2), (3,4), (5,6), (1,2), (3,4) ]  # Test data
cmn = collections.Counter(lis).most_common()  # Numbering based on occurrence
most = [e for e in cmn if (e[1] == cmn[0][1])]  # List of those most common
print(random.choice(most)[0])  # Print one of the most common at random



回答6:


Here is another example with no imports:

listAlphaLtrs = ['b','a','a','b','a','c','a','a','b','c','c','b','a','a','a']
dictFoundLtrs = {i:listAlphaLtrs.count(i) for i in listAlphaLtrs}
maxcnt = 0
theltr = 0
for ltr in dictFoundLtrs:
    ltrfound = ltr
    foundcnt = dictFoundLtrs[ltr]
    if foundcnt > maxcnt:
        maxcnt = foundcnt
        theltr = ltrfound
print('most: ' + theltr)

Sources: (please upvote answers in below link!)

https://stackoverflow.com/a/23240989/1447509



来源:https://stackoverflow.com/questions/18827897/python-get-most-frequent-item-in-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!