python - 发现字典中的最大值

标签 python dictionary max key-value-store

我试图找出字典中的最大值,但我遇到了一些麻烦。 这是我的代码:

def most_fans(dictionary):
    empty = ''
    for key in dictionary:
        if len(dictionary[key]) > next(dictionary[key]):
            empty = key
    print(empty)

我意识到我的代码存在问题,因为如果我有这样的字典:

fans={'benfica': ['joao','ana','carla'],
      'sporting': ['hugo','patricia'],
      'porto': ['jose']}

输出将是 'benfica''sporting'。因为 benfica 比 sporting 大,但 sporting 也比 porto 大。然而,这是我想出的最好的。

谁能告诉我一个合适的方法来做到这一点?

最佳答案

你可以只使用 max() 和一个键:

>>> max(fans, key=lambda team:len(fans[team]))
'benfica'

这里:

  • max(fans, ...) 遍历 fans 的键(即球队名称),根据某种标准寻找最大的元素;<
  • lambda 函数指定了该标准(在本例中,球队拥有的球迷数量)。

关于python - 发现字典中的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41434526/

相关文章:

python - 如何从 Keras 嵌入层获取词向量

c++ - 在 C++ 中找到 3 个数字中最小的

c++ - 查找 Mat 中的最小/最大值,同时忽略 -100

python - apache2用什么权限/用户写django日志

python - 如何内省(introspection) Cython C 扩展模块中定义的函数

python - 在 SLURM 中运行程序时如何保存打印语句?

python - Django 迭代列表中的字典并在模板中显示数据

python - 向 Pyramid 身份验证引入 "remember my name"和 "remember my password"选项

python - 了解Python中的map函数——索引重新分配

iphone - NSString 对象的最大长度是多少?