【问题标题】:How to print the key that has the most number of elements in its list?如何打印列表中元素数量最多的键?
【发布时间】:2019-10-19 21:25:57
【问题描述】:

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

我设法编写了一个函数来计算我的动物列表中的值的数量。我试图寻找一种方法来实现这一点,但是

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】:

    您可以为内置的max 函数提供key 参数来轻松完成此操作:

    animals = { 'a': ['horse'], 'b': ['baboon'], 'c': ['giraffe','donkey']}
    
    print(max(animals.keys(), key=lambda k:len(animals[k])))
    # prints 'c'
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-02
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多