Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing lists of objects with custom key

I sort some objects based on one of their attributes, using something like this:

sorted_list = sorted(unsorted_list, key=lambda x: x.my_attr)

Is there any way to sort a list of lists of these objects, in the same way that Python can sort lists of lists of integers? I can overload __cmp__(self, other) for these objects, but this throws up difficulties in an external package. The nesting may become arbitrarily deep too, so I don't think I can just use a list comprehension.

I was wondering if there was something where I could generate lists of the my_attrs and link this to the corresponding lists of objects. I can't think of a nice way to do it offhand.

like image 209
Kyle_S-C Avatar asked Nov 21 '22 09:11

Kyle_S-C


1 Answers

You can implement comparison functions on your data type and then rely on Python's sorting functions.

See similar question and answers: Python: Sort custom class without use of `key` argument?

In short, you can use total_ordering meta-class and implement __eq__ and __lt__ functions.

In your specific case, you may implement __eq__ like this:

def __eq__(self, other):
    return self.my_attr == other.my_attr

and similarly for __lt__.

like image 200
wap26 Avatar answered Nov 29 '22 05:11

wap26