可能重複:
In python, how do I take the highest occurrence of something in a list, and sort it that way?以一個列表,排序按熱門程度,然後刪除重複
大家好,
我正在尋找一種簡單的方法來排序列表通過流行度,然後刪除重複的元素。
例如,給出一個列表:
[8, 8, 1, 1, 5, 8, 9]
我會再與像一個列表結束了以下內容:
[8, 1, 5, 9]
可能重複:
In python, how do I take the highest occurrence of something in a list, and sort it that way?以一個列表,排序按熱門程度,然後刪除重複
大家好,
我正在尋找一種簡單的方法來排序列表通過流行度,然後刪除重複的元素。
例如,給出一個列表:
[8, 8, 1, 1, 5, 8, 9]
我會再與像一個列表結束了以下內容:
[8, 1, 5, 9]
@SilentGhost爲Python 2.7+提供了一個很好的解決方案。 2.6及以上的相對簡單的解決方案:但是
a = [8, 8, 1, 1, 5, 8, 9]
popularity = sorted(set(a), key=lambda x: -a.count(x))
[8, 1, 5, 9]
該解決方案是,昂貴的(因爲count
)。
這裏另一個臨時字典更好的解決方案:
a = [8, 8, 1, 1, 5, 8, 9]
d = {}
for i in a:
d[i] = d.get(i, 0) + 1
popularity = sorted(d, key=d.get, reverse=True)
>>> lst = [1, 1, 3, 3, 5, 1, 9]
>>> from collections import Counter
>>> c = Counter(lst)
>>> [i for i, j in c.most_common()]
[1, 3, 5, 9]
看到collections.Counter
文檔的鏈接到傳統版本 - 兼容的實現。
你應該給一個更好的例子。在你的,流行的順序是與數字的自然順序相同。如果你有兩個九號,會不會是'[1,3,9,5]'? – 2011-02-01 11:20:44
是的。對困惑感到抱歉! – 2011-02-01 11:22:42
@kahm:您無法按受歡迎程度對列表進行排序。您必須創建一些包含計數的其他中間結構。你看過什麼其他結構? – 2011-02-01 11:26:00