【发布时间】:2016-11-14 22:53:48
【问题描述】:
我正在编写一个函数来计算一个国家在字典中出现的次数并返回出现次数最多的国家。如果出现最多的国家/地区不止一个,则应返回国家/地区列表。
示例字典:
{'Leonardo da Vinci': [("Portrait of Isabella d'Este", 1499, 63.0, 46.0, 'chalk', 'France'), ('The Last
Supper', 1495, 460.0, 880.0, 'tempera', 'Italy')], 'Pablo Picasso': [('Guernica', 1937,
349.0, 776.0, 'oil paint', 'Spain')]}
由于法国、意大利和西班牙都只在这本词典中出现过一次,因此函数应该返回
countries_appeared_most(dictionary1())
['France', 'Italy', 'Spain']
如果其中一个国家/地区出现了 2 或 3 次,则该函数将仅返回该国家/地区。我下面的当前代码改为搜索出现次数最多的艺术家,但我相信一些小的更改可以帮助我返回出现次数最多的国家/地区。有人对如何做到这一点有建议吗?感谢您的帮助
代码:
def countries_appeared_most(db):
if not db:
return None
maxcount = max(len(v) for v in db.values())
themax = [k for k, v in db.items() if len(v) == maxcount]
themax.sort()
return themax
【问题讨论】:
标签: python python-3.x dictionary count