我有一个元组列表,我想得到最常出现的元组,但如果有“联合赢家”,它应该随机选择它们。
tups = [ (1,2), (3,4), (5,6), (1,2), (3,4) ]
所以我想要一些能够随机返回上述列表的(1,2)或(3,4)
您可以先使用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]
使用collections.Counter
:
>>> collections.Counter([ (1,2), (3,4), (5,6), (1,2), (3,4) ]).most_common()[0]
((1, 2), 2)
这是O(n log(n))
。
您可以先对列表进行排序,以便按频率对元组进行排序。之后,线性扫描可以从列表中获得最频繁的元组。总时间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)]
这个应该在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)
用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
这是另一个没有导入的例子:
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)
资料来源:(请在下面的链接中提出答案!)