Python: ¿Ordenar la clase personalizada sin usar el argumento `key`?

You can sort an array of myclass mediante el uso de la key argumento a la sorted función:

sortedlist = sorted(myclasses, key=lambda obj: obj.myproperty)

Is there a way to define a natural ordering for our class? Perhaps some magic method so that we don't have to pass in a key each time?

e.g.,

class myclass:
    def __init__(self,a,b):
        self.key1 = a
        self.key2 = b

    def __sortkey__(self):
        return self.key2

Or will it naturally work if we define __le__ ¿quizás?

preguntado el 29 de julio de 12 a las 00:07

3 Respuestas

Además de nuestras localidaded en __cmp__, you can also do it with the so-called "rich comparison operators" __eq__, __le__, __lt__, __gt__ y __ge__. Rather than defining all of them, you can use the functools.total_ordering class decorator in 2.7+/3.1+. __cmp__ is gone in 3.x.

Respondido 29 Jul 12, 00:07

Aun mejor. __le__ is easier to implement as I only need to return a bool. - mpen

Lo haría anulando __cmp__

class myclass:
    def __init__(self,a,b):
        self.key1 = a
        self.key2 = b

    def __cmp__(self, other):
        return cmp(self.key2, other.key2)

Respondido 29 Jul 12, 00:07

Ah. Nice! Couldn't find it under docs.python.org/library/functions.html#sorted - mpen

Ver esta pregunta anterior. The answer is that you can get away with just using __lt__, pero es mejor usar functools.total_ordering.

contestado el 23 de mayo de 17 a las 13:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.