Python中类的__key__参数 [英] __key__ parameter for classes in Python

查看:83
本文介绍了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()" 它要我创建ltgt ..方法.但是我想不使用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?

推荐答案

我将实现__lt____eq__,然后使用

I would implement __lt__ and __eq__ and then use the functools.total_ordering class decorator to get the rest of the comparison methods.

如果按照这种顺序对向量进行排序没有意义,那么您始终可以在sortsorted上使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆