Can I sort a list of objects by 2 keys?

2019-05-26 03:16发布

问题:

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)