Can I sort a list of objects by 2 keys?

杀马特。学长 韩版系。学妹 提交于 2019-12-10 10:38:43

问题


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

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

I am currently sorting like this:

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

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

Thx for any help.


回答1:


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

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

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

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


来源:https://stackoverflow.com/questions/29678659/can-i-sort-a-list-of-objects-by-2-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!