-1 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)]
Run Code Online (Sandbox Code Playgroud)
我不知道怎么排序.Python中是否有任何工具可以帮助解决这个问题或需要编写一些自定义函数?
您需要实现丰富的比较方法一样__lt__,并__ne__以能够整理你的类的列表在您的类.然而,__eq__如果我们装饰,我们可以逃避只实施其中的两个(以及其中一个不等式),而不是实现所有六个比较functools.total_ordering.
如果你想要一个字典排序,那么你首先进行比较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)
Run Code Online (Sandbox Code Playgroud)
现在,我们可以做到以下几点:
>>> 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)]
Run Code Online (Sandbox Code Playgroud)