2016-11-15 82 views
-1

我创建了一个函数,用于统计一个国家出现在字典中的次数,并返回出现频率最高的国家/地区。如果多于一个国家出现的话,那么它应该返回一个国家名单。无法统计字典中的国家

例词典:

{'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次功能将返回该国家。

我现在的代码下面我认为是接近解决方案,但我一直得到一个NameError匹配未定义。有谁知道我做错了什么?感谢您的帮助

代码:

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

[为什么你问同样的问题两次?](http://stackoverflow.com/questions/40599222/python-counting-countries-in-dictionary) –

+0

这是一个不同的问题,我遇到了新问题代码,所以我问什么是错的 – warrior4223

回答

0

首先,看Counter从集合。它已经做了你想做的事情。其次,你的问题是你的缩进。 matches仅在函数的范围内定义,但最后一行不缩进,因此不被视为函数的一部分。

+0

谢谢我知道这可能是一些简单的原因造成的问题 – warrior4223

0

试试这个:

所有的
from collections import Counter 

# unpack the tuples in the dictionary 
countries = [tup[-1] for val in painter_dict.values() for tup in val] 

# create a counter, get the maximum number of appearance 
counter = Counter(countries) 
max_count = max(counter.values()) 

# pull the countries of with values equal to the max_count 
appeared_most = [k for k in counter if counter[k]==max_count] 
+0

感谢您的回答,我得到了我的原代码工作 – warrior4223