如何在列表中找到最常见的元素,如果有平局,最后出现的元素是第一个?

use*_*683 4 python

基本上如果给出一个列表

events = [123,123,456,456,456,123]
Run Code Online (Sandbox Code Playgroud)

我希望它返回 456,因为上次看到 456 早于上次看到 123。

我制作了由初始数字列表的计数和索引组成的列表。我还制作了一个字典,其中键是事件(原始部分)的元素,hte 值是.count()键的值。

我真的不知道从哪里开始,可以使用一些帮助。

hug*_*own 5

方法

找到最常出现的项目 (Counter.most_common)。然后在这些候选中找到具有最小索引的项目(枚举到索引字典中,{index: key}.iteritems() 的最小值)。

代码

从@gnibbler 和 @Jeff 那里大肆窃取:

from collections import Counter

def most_frequent_first(events):
    frequencies = Counter(events)
    indexes = {event: i for i, event in enumerate(events)}
    most_frequent_with_indexes = {indexes[key]: key for key, _ in frequencies.most_common()}
    return min(most_frequent_with_indexes.iteritems())[1]

events = [123,123,456,456,456,123, 1, 2, 3, 2, 3]
print(most_frequent_first(events))
Run Code Online (Sandbox Code Playgroud)

结果

>>> print(most_frequent_first(events))
456
Run Code Online (Sandbox Code Playgroud)

代码

一段更好的代码将为您提供频率和索引,向您展示代码工作正常。这是一个使用 named_tuple 的实现:

from collections import Counter, namedtuple

frequent_first = namedtuple("frequent_first", ["frequent", "first"])

def most_frequent_first(events):
    frequencies = Counter(events)
    indexes = {event: i for i, event in enumerate(events)}
    combined = {key: frequent_first(value, indexes[key]) for key, value in frequencies.iteritems()}
    return min(combined.iteritems(), key=lambda t: (-t[1].frequent, t[1].first))

events = [123,123,456,456,456,123, 1, 2, 3, 2, 3]
print(most_frequent_first(events))
Run Code Online (Sandbox Code Playgroud)

结果

>>> print(most_frequent_first(events))
(456, frequent_first(frequent=3, first=4))
Run Code Online (Sandbox Code Playgroud)


Jef*_*eff 2

使用collections.counter

>>> import collections

>>> events = [123,123,456,456,456,123]
>>> counts = collections.Counter(events)
>>> print counts
Counter({456: 3, 123: 3})
>>> mostCommon = counts.most_common()
>>> print mostCommon
[(456, 3), (123, 3)]
Run Code Online (Sandbox Code Playgroud)

这是最困难的部分。