如何根据对象的属性对象列表进行排序?我有一个Python对象列表,我想根据对象本身的属性进行排序。清单如下:>>> ut[<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>,
<Tag: aes>, <Tag: ajax> ...]每个对象都有一个计数:>>> ut[1].count1L我需要按下降的计数对列表进行排序。我已经看到了几种方法,但我正在寻找Python中的最佳实践。
3 回答

元芳怎么了
TA贡献1798条经验 获得超7个赞
operator.attrgetter("count")
try: import operatorexcept ImportError: keyfun= lambda x: x.count # use a lambda if no operator moduleelse: keyfun= operator.attrgetter("count") # use operator since it's faster than lambdaut.sort(key=keyfun, reverse=True) # sort in-place
添加回答
举报
0/150
提交
取消