我已经为这个问题努力了一段时间,我正在努力弄清楚如何在Python中正确完成它。基本上,我有一个对象列表,每个对象都有几个属性,其中最著名的是name属性。我想对该列表进行排序并打印最常出现的名称。我试图做这样的事情:
sorted(list, key=lambda h:(h.name), reverse = True)
但是这似乎按字母顺序排序,而且我不确定如何使它按频率工作。是否有人对我如何实现此目标有建议或想法?
我会使用collection.Counter
的帮助。任何将所有逻辑推入key
的sorted
功能的尝试都将导致非常难以理解或效率低下的解决方案。
也不要使用list
作为变量名。
## prepping stuff ##
import random
class Foo:
def __init__(self):
self.name = random.randint(1, 5)
def __repr__(self):
return str(self.name)
list_of_stuff = [Foo() for _ in range(10)]
print(list_of_stuff)
# [1, 3, 1, 2, 1, 5, 5, 4, 4, 4]
## actual answer ##
from collections import Counter
c = Counter(h.name for h in list_of_stuff)
# Counter({4: 3, 2: 3, 3: 2, 1: 2})
print(sorted(list_of_stuff, key=lambda h: c.get(h.name, 9999), reverse=True))
# ^ or any other sentinel value
# you want to use in case of
# missing value,
# otherwise Counter
# will use 0.
# MUST be comperable
# with int
输出
[1, 1, 1, 4, 4, 4, 5, 5, 3, 2]