如何排序对象列表

时间:2014-06-12 03:50:42

标签: 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中是否有任何工具可以帮助解决这个问题,还是需要编写一些自定义函数?

4 个答案:

答案 0 :(得分:6)

您需要在班级中实施__lt____ne__之类的rich comparison methods,以便能够对班级的实例列表进行排序。但是,如果我们用functools.total_ordering进行装饰,我们可以逃避只实现其中两个(__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)]

答案 1 :(得分:3)

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

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

答案 2 :(得分:1)

这完全取决于您计划排序的内容。但是,无论你是什么,你可能正在寻找一个lambda函数。假设你想按self.a属性排序,你可以按照这样的方式编写

#[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)]

答案 3 :(得分:1)

正如@senshin已经解释的那样,有一种方法可以使对象有序。如果Example是固有的,并且也可以使用例如排序,那么这是有效的。比较独立对象。但是,如果您的排序顺序可能会有所不同,那么您需要sortedlist.sort key参数,而operator module functions可以使其更优雅:

from operator import attrgetter
sorted(alist, key=attrgetter('a'))      # sort just by a
sorted(alist, key=attrgetter('c', 'b')) # sort by c then by b
相关问题