我有一个元组列表,我想获取最频繁出现的元组,但是如果有“联合获胜者”,它应该随机选择它们。Python:获取列表中最常见的项目
tups = [ (1,2), (3,4), (5,6), (1,2), (3,4) ]
所以我想要的东西,会在回报(1,2)或随机对以上列举
我有一个元组列表,我想获取最频繁出现的元组,但是如果有“联合获胜者”,它应该随机选择它们。Python:获取列表中最常见的项目
tups = [ (1,2), (3,4), (5,6), (1,2), (3,4) ]
所以我想要的东西,会在回报(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]
(3,4)你可以先排序列表以获得通过频率排序的元组。之后,线性扫描可以从列表中获得最频繁的元组。总体时间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)]
使用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(n)中做。您只需计算频率,获得最大值,然后获取所有频率最高的项目。至少有4人不知道:) –
在O(n)中不可能做到这一点,计算所有频率本身需要某种散列表。 – simonzack
AFAIK计数器实现为字典,字典的设置元素平均为“O(1)”。在你的回答中,'most_common()'方法会做所有元素的排序,所以它会是最重的部分 - O(n log(n)) –
这一个应该做你的任务在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)
这不是'O(n)',想想所有元素都不一样的情况。 – simonzack
https://wiki.python.org/moin/TimeComplexity字典中元素的设置为O(1)平均 –
最常见的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
@Juddling实际上,你不需要most_common() - 看到我的回答 –
@RomanPekar我明白了,为什么我要避免使用most_common()? – Juddling
如果我没有弄错,most_common()会对整个列表进行排序,而您只需要最大频率 –