我有一個元組列表,我想獲取最頻繁出現的元組,但是如果有「聯合獲勝者」,它應該隨機選擇它們。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()會對整個列表進行排序,而您只需要最大頻率 –