基本上如果给出一个列表
events = [123,123,456,456,456,123]
我希望返回 456 ,因为456最后一次出现的时间比最后一次看到的还要早。
我制作了由初始数字列表的计数和索引组成的列表。
我还创建了一个字典,其中键是事件中的元素(原始部分),而hte值是键的.count()
。
我真的不知道从哪里开始可以使用一些帮助。
答案 0 :(得分:4)
查找最常出现的项目(Counter.most_common)。然后在那些具有最小索引的候选项中找到该项(枚举到索引字典中,min为{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))
>>> print(most_frequent_first(events))
456
更好的代码将为您提供频率和索引,向您显示代码正常工作。这是一个使用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))
>>> print(most_frequent_first(events))
(456, frequent_first(frequent=3, first=4))
答案 1 :(得分:3)
使用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)]
这是困难的部分。
答案 2 :(得分:2)
>>> from collections import Counter
>>> events = [123,123,456,456,456,123]
>>> c = Counter(events)
>>> idxs = {k: v for v,k in enumerate(events)}
>>> sorted(c.items(), key=lambda (k,v): (-v, idxs[k]))
[(456, 3), (123, 3)]