理解中的最大功能

时间:2017-10-21 14:39:01

标签: python python-3.x

我正在尝试理解此代码中的max函数。如果我使用我的常识,我把max函数放在这个k,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 个答案:

答案 0 :(得分:0)

您不需要最大值,但需要最长值。 使用key的{​​{1}}参数:

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