Python中类的__key__参数 [英] __key__ parameter for classes in Python
本文介绍了Python中类的__key__参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个向量数组,我想按长度对它们进行排序:
I have an array of vectors and I want to sort them by length:
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(a, b):
return Vector(a.x + b.x, a.y + b.y)
def __str__(a):
return str(a.x) + ' ' + str(a.y) + '\n'
def __key__(self):
return self.x * self.x + self.y * self.y
a = []
a.append(Vector(1,2))
a.append(Vector(1, 1))
a.sort()
print("".join(map(str,a)))
它说:不可排序的类型:Vector()< Vector()"
它要我创建lt
,gt
..方法.但是我想不使用cmp
进行排序.有可能吗?
It says: "unorderable types: Vector() < Vector()"
It wants me to create lt
, gt
.. methods. But I want to sort without using cmp
. Is it possible?
推荐答案
I would implement __lt__
and __eq__
and then use the functools.total_ordering
class decorator to get the rest of the comparison methods.
如果按照这种顺序对向量进行排序没有意义,那么您始终可以在sort
或sorted
上使用key
关键字:
If it doesn't make sense to have your vectors ordered like that, then you can always just use the key
keyword to sort
(or sorted
for that matter):
mylist.sort(key = lambda v: v.x**2 + v.y**2)
这篇关于Python中类的__key__参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文