2017-10-21 56 views
-1

我想了解此代碼中的最大函數。如果我用我的常識,我把這個max函數(len(v))放在下面而不是下面。但是這給我一個語法錯誤。 max函數如何在這裏運行?理解最大函數

animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']} 

animals['d'] = ['donkey'] 
animals['d'].append('dog') 
animals['d'].append('dingo') 

def biggest(aDict): 
    ''' 
    aDict: A dictionary, where all the values are lists. 

    returns: The key with the largest number of values associated with it 
    ''' 
    # List comprehension 
    return max((k, len(v)) for k, v in aDict.items())[0] 

print(biggest(animals)) 
+1

它不表現任何不同。 len返回一個int並且max(5)沒有意義,因爲5不是您可以從中獲得最大值的數字的集合。你不會得到一個語法錯誤,但是,你會得到一個TypeError – jonatan

+0

是的,你是對的len。但是animals.items()賦予dict_items([''',''aardvark']),('b',['baboon']),('c',['coati']),('d' ,['驢','狗','丁當'])])。爲什麼max認爲權利但不是左邊? – Mearex

+0

你不應該假設max會選擇具有最大長度的第二個值的元組 - 這是非常具體的。你可以使用max的'key'參數來提取元組應該被比較的值。 – jonatan

回答

0

你不想要最大的密鑰,而是最長的值。 使用key說法max

from operator import itemgetter 

animals = {'a': ['aardvark', 'donkey', 'dog'], 'b': ['baboon'], 'c': ['coati']} 

def biggest(aDict): 
    ''' 
    aDict: A dictionary, where all the values are lists. 

    returns: The key with the largest number of values associated with it 
    ''' 
    # List comprehension 
    return max(((k, len(v)) for k, v in aDict.items()), key=itemgetter(1))[0] 

print(biggest(animals)) 

輸出:

a 

替代解決方案:

max(animals.items(), key=lambda item: len(item[1]))[0]