【发布时间】:2013-12-25 13:26:44
【问题描述】:
我正在尝试根据元素的属性在列表中选择最常见的项目。
a1 = Myclass(name='a')
a2 = Myclass(name='a')
b1 = Myclass(name='b')
l = [a1,a2,b1]
if most_common(l, attr_name='name') in [a1, a2]:
# I want this true
# 'a' is the most occured 'name'
基本上我想修改代码https://stackoverflow.com/a/1520716/433570
key = operator.itemgetter(0) 然后 operator.attrgetter(attr_name)
想知道这是否可能?
【问题讨论】:
-
有什么理由不使用
Counter?喜欢collections.Counter(x.name for x in l).most_common(1)