我可以按 2 个键对对象列表进行排序吗? [英] Can I sort a list of objects by 2 keys?

查看:42
本文介绍了我可以按 2 个键对对象列表进行排序吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程(精简):

I have the following class (trimmed down):

class DiskInstance(object):

    def __init__(self, name, epoch, size)
        self.name   = name
        self.epoch  = epoch
        self.size   = size

然后我定义一个外部函数(在上面的类之外):

Then I define a external function (external to the class above):

def getepoch(object):
    return object.epoch

然后我实例化这个类的几个对象并附加到一个名为 DISKIMAGES 的列表中.

I then instantiate several objects of this class and append to a list called DISKIMAGES.

我目前是这样排序的:

for image in sorted(DISKIMAGES, key=getedate, reverse=True):

有什么办法可以先按 getedate 再按大小排序?

Is there any way I can sort first by getedate and then by size?

感谢任何帮助.

推荐答案

如果你想先按纪元然后按大小排序,这应该可行:

If you want to sort by epoch and then size, this should work:

sorted(DISKIMAGES, key=lambda x: (x.epoch, x.size), reverse=True)

或者如@chepner所指出的,您可以使用operator.attrgetter方法

or as pointed out by @chepner, you can use the operator.attrgetter method

import operator
sorted(DISKIMAGES, key=operator.attrgetter('epoch', 'size'), reverse=True)

这篇关于我可以按 2 个键对对象列表进行排序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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