2017-06-02 21 views
0

我對此代碼感到困惑,allmax傳遞hand_rank函數作爲密鑰,但是在allmax的定義中,它將密鑰設置爲None,然後hand_rank如何傳遞給這個allmax函數?Python:如何將密鑰傳遞到默認值爲None的函數

def poker(hands): 
    "Return a list of winning hands: poker([hand,...]) => [hand,...]"   
    return allmax(hands, key=hand_rank) 


def allmax(iterable, key=None): 
    "Return a list of all items equal to the max of the itterable." 
    result, maxval = [],None 
    key = key or (lambda x:x) 
    for x in iterable: 
     xval = key(x) 
     if not result or xval > maxval: 
      result,maxval = [x],xval 
     elif xval == maxval: 
      result.append(x) 
    return result 
+3

'key = None'提供一個默認值,以防調用程序不提供密鑰。發佈前請閱讀文檔。這個句法特徵被稱爲「關鍵字參數」。 – Prune

+0

這裏沒有足夠的代碼來查看發生了什麼。什麼是'hand_rank',這個定義在哪裏,什麼叫什麼?請參閱[mcve] –

+0

謝謝,下次請注意! – Lucy

回答

1

這是一個默認參數。 key只會默認爲,如果hand_rank從未傳遞過,或者傳遞爲空。您可以設置默認的參數是相當多的東西,

def allmax(iterable, key=[])

然而,在這種情況下,它看起來像你想避免更新一個空列表。如果密鑰設置爲[],它將在稍後的調用中添加到列表中,而不是從新列表開始。

這是可變默認參數的good explanation,以及爲什麼None用於停止意外行爲。這裏有空列表參數問題someone else on Stack Overflow。在函數定義參數

0

默認值是僅用於如果該函數被調用,而不該參數

理解很簡單的例子:

定義

def print_it(message = "Hello!"): 
    print(message) 

調用它沒有參數:

print_it();       # The default value will be used 

使輸出

您好!

調用它參數

print_it("Give me your money!") # The provided value will be used 

給人的輸出

「給我你的錢!」

默認值是完全忽略

相關問題