Python排序-对象列表 [英] Python sorting - A list of objects

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

问题描述

如果可能的话,我想使用somelist.sort()方法执行此操作.

I'd like to use the somelist.sort() method to do this if possible.

我有一个包含对象的列表,所有对象都有一个成员变量resultType,它是一个整数.我想使用此数字对列表进行排序.

I have a list containing objects, all objects have a member variable resultType that is an integer. I'd like to sort the list using this number.

我该怎么做?

谢谢!

推荐答案

somelist.sort(key = lambda x: x.resultType)

这是您经常会看到用过的做同一件事的另一种方法:

Here's another way to do the same thing that you will often see used:

import operator
s.sort(key = operator.attrgetter('resultType'))

如果您还没有考虑过 sorted ,还没看过它不会修改原始列表,而是返回一个新的排序列表.

You might also want to look at sorted if you haven't seen it already. It doesn't modify the original list - it returns a new sorted list.

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

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