对类实例Python的列表进行排序 [英] Sort a list of Class Instances Python

查看:144
本文介绍了对类实例Python的列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类实例的列表-

I have a list of class instances -

x = [<iteminstance1>,...]

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

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

编辑:python中的list有一个叫做sort的东西.我可以在这里使用吗?如何指导此功能使用我的score属性?

EDIT: The list in python has something called sort. Could I use this here? How do I direct this function to use my score attribute?

推荐答案

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

如果要对x进行原位排序,还可以:

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

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

这篇关于对类实例Python的列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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