I am not sure how the return works in the following compare function? Why can it return the format like this?
def func(self, num):
num = sorted([str(x) for x in num], cmp=self.compare)
def compare(self, a, b):
return [1, -1][a + b > b + a]
It's not returning two lists. It's returning one of the two values from the first list. Consider this rewriting:
def compare(self, a, b):
possible_results = [1, -1]
return possible_results[a + b > b + a]
It's taking advantage of the fact that True in Python is treated as the value 1, and False is treated as the value 0, and using those as list indices.
The boolean value of False is zero and the boolean value of True is one. They can both be used as indexes into a list:
# Normal indexing with integers
>>> ['guido', 'barry'][0]
'guido'
>>> ['guido', 'barry'][1]
'barry'
# Indexing with booleans
>>> ['guido', 'barry'][False]
'guido'
>>> ['guido', 'barry'][True]
'barry'
# Indexing with the boolean result of a test
>>> ['guido', 'barry'][5 > 10]
'guido'
>>> ['guido', 'barry'][5 < 10]
'barry'
Hope that makes it all clear :-)
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