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_attr
s and link this to the corresponding lists of objects. I can't think of a nice way to do it offhand.
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__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With