如何对对象列表排序

2024-04-24 22:39:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习python,我不知道使用许多属性对对象列表进行排序的最佳方法是什么。现在我有了这个

class Example:      
    def __init__(self, a,b,c):
        self.a = a
        self.b = b
        self.c = c


List = [Example(3,1,5), Example(2,1,2), Example(2,2,2),  Example(1,4,1),Example(1,4,5), Example(1,4,2)] 

我不知道如何分类。Python中是否有任何工具可以帮助实现这一点,或者需要编写一些自定义函数?你知道吗


Tags: 工具对象方法函数self列表属性排序
3条回答

您可以按以下方式按多个项目排序:

List.sort(key=lambda e: [e.a, e.b, e.c])
# or
List.sort(key=operator.attrgetter('a', 'b', 'c'))

您需要在类中实现rich comparison methods,比如__lt____ne__,以便能够对类的实例列表进行排序。但是,如果我们用^{}来修饰,我们就可以只实现其中的两个(__eq__和一个不等式),而不是实现所有六个比较。你知道吗

如果您想要一个字典排序,那么您首先在a上进行比较,然后如果并列,则在b上进行比较,如果仍然并列,则在c上进行比较,请参见以下内容:

import functools

@functools.total_ordering
class Example:      
    def __init__(self, a,b,c):
        self.a = a
        self.b = b
        self.c = c
    def __eq__(self, other):
        if self.a == other.a and self.b == other.b and self.c == other.c:
            return True
        else:
            return False
    def __lt__(self, other):
        if self.a < other.a:
            return True
        elif self.a == other.a and self.b < other.b:
            return True
        elif self.a == other.a and self.b == other.b and self.c < other.c:
            return True
        else:
            return False
    def __repr__(self): # included for readability in an interactive session
        return 'Example({}, {}, {})'.format(self.a, self.b, self.c)

现在,我们可以做以下工作:

>>> lst = [Example(3,1,5), Example(2,1,2), Example(2,2,2),  Example(1,4,1),Example(1,4,5), Example(1,4,2)]
>>> lst
[Example(3, 1, 5), Example(2, 1, 2), Example(2, 2, 2), Example(1, 4, 1), Example(1, 4, 5), Example(1, 4, 2)]
>>> lst.sort()
>>> lst
[Example(1, 4, 1), Example(1, 4, 2), Example(1, 4, 5), Example(2, 1, 2), Example(2, 2, 2), Example(3, 1, 5)]

这一切都取决于你的排序计划。但是,不管是什么,您可能正在寻找lambda函数。假设您想按self排序。您可以这样编写排序属性

#[Example(3, 1, 5), Example(2, 1, 2), Example(2, 2, 2), Example(1, 4, 1), Example(1, 4, 5), Example(1, 4, 2)]

List.sort(key=lambda x: x.a, reverse=False)

#[Example(1, 4, 1), Example(1, 4, 2), Example(1, 4, 5), Example(2, 1, 2), Example(2, 2, 2), Example(3, 1, 5)]

相关问题 更多 >