I would like to sort a list by referring to the elements being compared. So if one element has attribute X to other element, I want it first.
Simple example:
class Apple:
def can_eat(self, other):
return False
class Human:
def can_eat(self, other):
# can eat humans or apples. No other food, because it's an example
if isinstance(other, Human):
return True
return isinstance(other, Apple)
class Thing:
def can_eat(self, other):
return False
apple = Apple()
human = Human()
things = [apple, human, apple]
things.sort(?) # I'd want human before or after apple (depending on reverse)
Is there a way I can sort a list on this in python?
To be clear: The problem I have is that using something like this answer: sort list of objects by return of object method
does not work for me, as I still don't see how to access both objects, i.e. how to specify the lambda function to, when comparing human vs. apple, call human.can_eat(apple) or vice versa.
Simply closing the question as "related" did not explain this to me, so please either close with a question that does answer mine, or fill in the gaps. Thank you.