Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

python - 如何根据对象的属性对对象列表进行排序?(How to sort a list of objects based on an attribute of the objects?)

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

(我有一个Python对象列表,我想按对象本身的属性对其进行排序。)

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.

(我已经看到了几种方法,但是我正在寻找Python的最佳实践。)

  ask by Nick Sergeant translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
# 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 .

(有关按键排序的更多信息。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...