对类实例列表进行排序 Python

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4010322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:50:11  来源:igfitidea点击:

Sort a list of Class Instances Python

pythonsorting

提问by

I have a list of class instances -

我有一个类实例列表 -

x = [<iteminstance1>,...]

among other attributes the class has scoreattribute. How can I sort the items in ascending order based on this parameter?

在其他属性中,该类具有score属性。如何根据此参数按升序对项目进行排序?

EDIT: The listin python has something called sort. Could I use this here? How do I direct this function to use my scoreattribute?

编辑list在 python 中有一个叫做sort. 我可以在这里使用这个吗?如何指示此函数使用我的score属性?

采纳答案by Ned Batchelder

import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:

如果您想就地对 x 进行排序,您还可以:

x.sort(key=operator.attrgetter('score'))

回答by kindall

In addition to the solution you accepted, you could also implement the special __lt__()("less than") method on the class. The sort()method (and the sorted()function) will then be able to compare the objects, and thereby sort them. This works best when you will only ever sort them on this attribute, however.

除了您接受的解决方案之外,您还可以__lt__()在类上实现特殊(“小于”)方法。然后该sort()方法(和sorted()函数)将能够比较对象,从而对它们进行排序。但是,当您仅根据此属性对它们进行排序时,此方法效果最佳。

class Foo(object):

     def __init__(self, score):
         self.score = score

     def __lt__(self, other):
         return self.score < other.score

l = [Foo(3), Foo(1), Foo(2)]
l.sort()