python - 如何在Python语言中找到字典中最大元素的键?

标签 python python-3.x

10天以来我一直遇到问题,我试图在书籍和互联网上寻找解决方案,但找不到。这里有一个例子:

animals = { 'a': ['lion'], 'b': ['baboon'], 'c': ['goat']}
animals['d'] = ['donkey']
animals['d'].append('elephant')
animals['d'].append('swan')

我必须编写一个方法largest来找出与最长列表关联的键。在示例中,输出应该是

largest(animals)
'd'

最佳答案

使用内置的 max() 和用于键之间比较的自定义函数。

animals = { 'a': ['lion'], 'b': ['baboon'], 'c': ['goat']}
animals['d'] = ['donkey']
animals['d'].append('elephant')
animals['d'].append('swan')

largest = max(animals, key=lambda k: len(animals[k]))

使用 max 函数的 key 参数可以更改比较元素的标准。 在这种情况下,字典的根据字典animals中存储在该键下的列表的长度进行比较。

关于python - 如何在Python语言中找到字典中最大元素的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42001962/

相关文章:

python - 用Python中另一个列表中的项目替换满足某些条件的列表元素

python - 我如何知道一个立方体何时与另一个移动的立方体碰撞?

python - 如何使用 eyed3 模块从 Mp3 中删除现有的专辑封面图像

python - Python 中的副作用

python - 如何使用 ctypes 和线程为 C 回调函数分配内存

python - 在 attrs 类中为 init 参数添加类型提示

python - 当使用Kivy Clock设置 bool 标志时,如何触发回调?

html - 从 soup 对象中提取包含所需字符串的行

python-3.x - 如何根据 Pandas 中的其他列根据另一列中的间隔填充缺失值?

python - 模块 'path' 中无名称 'django.urls'