如何打印列表中元素数量最多的键?

问题描述 投票:0回答:1

我想编写一个函数,该函数将在字典中返回键的名称,以使键在其列表中具有最多的元素。

我设法编写了一个对我的动物列表中的值进行计数的函数。我试图寻找一种方法来实现这一目标,但

animals = { 'a': ['horse'], 'b': ['baboon'], 'c': ['giraffe','donkey']}

def how_many(dic):
    count = 0
    for x in animals: 
        if isinstance(animals[x], list): 
            count += len(animals[x]) 
    print(count)


def biggest(dic):
    p = []
    for i in range(len(animals)):
        x = how_many(dic[i])
        p.append(x)

#stuck here

最大(dic)函数应打印C。

python python-3.x
1个回答
3
投票
animals = { 'a': ['horse'], 'b': ['baboon'], 'c': ['giraffe','donkey']} print(max(animals.keys(), key=lambda k:len(animals[k]))) # prints 'c'
© www.soinside.com 2019 - 2024. All rights reserved.