我试图找出字典中的最大值,但我遇到了一些麻烦。 这是我的代码:
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/