-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))
它不表现任何不同。 len返回一个int并且max(5)没有意义,因为5不是您可以从中获得最大值的数字的集合。你不会得到一个语法错误,但是,你会得到一个TypeError – jonatan
是的,你是对的len。但是animals.items()赋予dict_items([''',''aardvark']),('b',['baboon']),('c',['coati']),('d' ,['驴','狗','丁当'])])。为什么max认为权利但不是左边? – Mearex
你不应该假设max会选择具有最大长度的第二个值的元组 - 这是非常具体的。你可以使用max的'key'参数来提取元组应该被比较的值。 – jonatan