如何使用特定键对Python类实例列表进行排序?

时间:2017-09-06 13:20:31

标签: python class sorting instance

我需要使用代表XP的第三个值对这个实例列表进行排序。我的函数使用CodeFighter(*codefighter)创建CodeFighter类的实例,我不确定如何在不返回值的情况下对其进行排序?

这些是我用来创建实例的值:

[["Warrior", "1", "1050"], ["Ninja!", "21", "995"], ["Recruit", "3", "995"]]

def sortCodefighters(codefighters):
    res = [CodeFighter(*codefighter) for codefighter in codefighters]
    res.sort(reverse=True)
    return list(map(str, res))

class CodeFighter:
    def __init__(self,name,id,xp):
        self.name=name
        self.id=int(id)
        self.xp =int(xp)
    ??????

1 个答案:

答案 0 :(得分:1)

'您的类不需要返回值,它需要一个可用于排序的属性。在您的情况下,您想使用' XP'要排序的价值。您可以使用运算符类使用属性' XP':

对类进行排序
import operator


class CodeFighter:
    def __init__(self,name,id,xp):
        self.name=name
        self.id=int(id)
        self.xp =int(xp)

    def __str__(self):
        return 'Name: %s, ID: %s, XP: %s' % (self.name, self.id, self.xp)


def sortCodefighters(codefighters, reversed=False):
    res = [CodeFighter(*codefighter) for codefighter in codefighters]
    return sorted(res, key=operator.attrgetter('xp'), reverse=reversed)


fighters = [["Warrior", "1", "1050"], ["Ninja!",  "21", "965"], ["Recruit", "3", "995"]]
fighters = sortCodefighters(fighters, reversed=True)
for fighter in fighters:
    print(fighter)

>> Name: Warrior, ID: 1, XP: 1050
>> Name: Recruit, ID: 3, XP: 995
>> Name: Ninja!, ID: 21, XP: 965

如果在调用sortCodefighters函数时翻转反转值:

fighters = [["Warrior", "1", "1050"], ["Ninja!",  "21", "965"], ["Recruit", "3", "995"]]
fighters = sortCodefighters(fighters, reversed=False)
for fighter in fighters:
    print(fighter)

>> Name: Ninja!, ID: 21, XP: 965
>> Name: Recruit, ID: 3, XP: 995
>> Name: Warrior, ID: 1, XP: 1050