我尝试根据一些非平凡的比较逻辑对对象列表进行排序,但发现很困难,因为在Python中,自定义排序函数只需要一个参数。例如,在Java中,sort函数会有对object1
和object2
的引用,这样比较它们就很简单了。你知道吗
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)
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')]
def my_sort(key):
# Sort by first element (letter).
#
# If the letter is the same, fallback to sorting by the
# 2nd element (number), but the logic of this comparison depends
# on `pt_type`:
# -If Point1 and Point2 both have type 'start', pick the higher number first.
# -If Point1 and Point2 both have type 'end', pick the lower number first.
# -If Point1 and Point2 have different types, pick the 'start' type first.
return key.char
print(sorted(arr, key=my_sort))
预期的排序顺序应为:
[Point('A', 6, 'start'), Point('A', 3, 'start')
Point('B', 2, 'end'), Point('B', 7, 'end'),
Point('C', 9, 'start'), Point('C', 1, 'end')]
我甚至不知道如何开始实现所需的逻辑,所以如果能朝着正确的方向努力,我将不胜感激。你知道吗
您可以将排序作为类的属性,然后使用
sorted
。这种方法的好处是:无需额外的努力,您就可以通过比较运算符(如>
、<
、==
)相互比较对象。你知道吗指定
__eq__
和__lt__
方法至少应该指定
__eq__
和__lt__
方法:添加其他比较方法,例如} 简化:
__gt__
、__ge__
等,可以通过^{示例
我将使用以下
key
函数:输出
key函数创建一个元组用作键,第一个元素是字母,如果节点类型为“start”,则第二个元素为0,如果节点类型为“end”,则为1。最后一个元素的类型为“start”时为负,类型为“end”时为正。你知道吗
您想使用
cmp
参数来sorted
,它接受两个参数的比较函数: https://docs.python.org/2/library/functions.html#sorted作为参考,
key
函数将从每个被排序的项中计算一个派生值,并根据该值进行排序,例如,要按对中的第二个值对一个对列表进行排序,可以执行:sorted(items, key=lambda x: x[1])
相关问题 更多 >
编程相关推荐