Вы можете сделать сортировку свойством своего класса, затем использовать sorted
. Преимущество этого метода: без дополнительных усилий вы можете сравнивать объекты друг с другом с помощью таких операторов сравнения, как >
, <
, ==
.
Укажите __eq__
и __lt__
методы
Как минимум, вы должны указать __eq__
и __lt__
методы:
class Point:
def __init__(self, char, num, pt_type):
self.char = char
self.num = num
self.pt_type = pt_type # 'start' or 'end'
def __str__(self):
return str([self.char, str(self.num), self.pt_type])
def __repr__(self):
return str(self)
def __eq__(self, other):
return self.char == other.char and self.pt_type == other.pt_type
def __lt__(self, other):
if self.char != other.char:
return self.char < other.char
if (self.pt_type == 'start') and (other.pt_type == 'start'):
return self.num > other.num
elif (self.pt_type == 'end') and (other.pt_type == 'end'):
return self.num < other.num
else:
return self.pt_type == 'start'
Добавление других методов сравнения, таких как __gt__
, __ge__
и т. Д., Может быть упрощено с помощью functools.total_ordering
:
from functools import total_ordering
@total_ordering
class Point:
def __init__(self, ...):
# initialization logic
def __eq__(self, other):
# as before
def __lt__(self, other):
# as before
Пример
arr = [Point('C', 1, 'end'), Point('C', 9, 'start'),
Point('B', 7, 'end'), Point('B', 2, 'end'),
Point('A', 3, 'start'), Point('A', 6, 'start')]
print(sorted(arr))
[['A', '6', 'start'],
['A', '3', 'start'],
['B', '2', 'end'],
['B', '7', 'end'],
['C', '9', 'start'],
['C', '1', 'end']]