Python:获取列表中最常用的项目

时间:2013-09-16 12:20:24

标签: python list group-by max

我有一个元组列表,我想获得最常出现的元组但是如果有“联合获胜者”则应该随机选择它们。

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

所以我想要的东西会随机返回(1,2)或(3,4)上面的列表

6 个答案:

答案 0 :(得分:10)

使用collections.Counter

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

这是O(n log(n))

答案 1 :(得分:2)

您可以先使用Counter查找最重复的元组。然后找到所需的元组,最后随机化并获得第一个值。

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 :(得分:1)

您可以先对列表进行排序,以便按频率对元组进行排序。之后,线性扫描可以从列表中获得最频繁的元组。总时间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)]

答案 3 :(得分:1)

这个人应该在o(n)时间内完成你的任务:

>>> 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)

答案 4 :(得分:0)

使用collections.Counter计数,然后随机选择最常见的:

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

答案 5 :(得分:0)

这是另一个没有导入的示例:

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)

来源: (请在下面的链接中回答答案!)

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