Python在字典中计数国家 [英] Python Counting countries in dictionary

查看:184
本文介绍了Python在字典中计数国家的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个函数,计算一个国家在字典中出现的次数,并返回出现最多的国家。

I'm writing a function that counts the number of times a country appears in a dictionary and returns the country that appeared the most. If more then one country appears the most then it should return a list of the countries.

例句字典:

{'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')]}

由于法国,意大利和西班牙都只出现一次在这个字典中函数应该返回

Since France, Italy, and Spain all only appear once in this dictionary the function should return

countries_appeared_most(dictionary1())

['France', 'Italy', 'Spain']

如果这些国家之一出现了2或3次,函数将只返回那个国家。我目前的代码,而不是搜索的艺术家出现最多,但我相信一些小的变化可以帮助我,而不是返回出现最多的国家。有没有人如何这样做的建议?感谢您的帮助

If one of those countries had instead appeared 2 or 3 times the function would return just that country. The current code I have below instead searches for the artist that appears the most but I believe a couple small changes could help me instead return the country that appears the most. Does anyone have advice on how to do this? Thanks for the help

代码:

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


推荐答案

counter = {}
for painting_list in db.values():
    for painting in painting_list:
        country = painting[-1]
        counter[country] = counter.get(country, 0) + 1
maxcount = max(counter.values())
themax = [k for k, count in counter.items() if count == maxcount]

这篇关于Python在字典中计数国家的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆