如何根据对象的属性对对象列表进行排序? [英] How to sort a list of objects , based on an attribute of the objects?

查看:110
本文介绍了如何根据对象的属性对对象列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python对象的列表,我想通过对象本身的属性来排序。列表如下:

 >>> ut 
[< Tag:128>,< Tag:2008>,< Tag:<>,< Tag:actionscript> ;,< Tag:addresses>,
< Tag :aes>,< Tag:ajax> ...]

每个对象都有一个计数:


$ b b

 >>> ut [1] .count 
1L

我需要按计数对列表排序



我已经看过几种方法,但我正在寻找Python的最佳实践。

 #对列表进行排序... 
ut.sort(key = lambda x:x.count,reverse = true)

#要返回一个新的列表,使用sorted()内置函数...
newlist = sorted(ut,key = lambda x:x.count,reverse = True)

更多 sort by keys»


I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like:

>>> ut
[<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>,
 <Tag: aes>, <Tag: ajax> ...]

Each object has a count:

>>> ut[1].count
1L

I need to sort the list by number of counts descending.

I've seen several methods for this, but I'm looking for best practice in Python.

解决方案

# To sort the list in place...
ut.sort(key=lambda x: x.count, reverse=True)

# To return a new list, use the sorted() built-in function...
newlist = sorted(ut, key=lambda x: x.count, reverse=True)

More on sorting by keys »

这篇关于如何根据对象的属性对对象列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆