2015-05-26 112 views
3

我不確定在以下比較函數中返回如何工作?爲什麼它能返回這樣的格式?返回兩個列表python?

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] 
+0

看看這樣說:-1,如果A + B> B + A否則1(如由答案覆蓋 - 使用等同於1/True和0/False的數組索引)。 – greg

回答

6

它沒有返回兩個列表。它返回第一個列表中的兩個值之一。考慮這個改寫:

def compare(self, a, b): 
     possible_results = [1, -1] 
     return possible_results[a + b > b + a] 

它採取的是True在Python被視爲價值1,並且False被視爲價值0,並利用這些作爲列表索引的事實。

3

布爾值False爲零且布爾值爲True爲爲1。它們都可以作爲索引到一個列表:

# 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' 

希望,它使所有清楚:-)