首页 > 解决方案 > 如何在没有库的情况下创建计数器?

问题描述

我想建立一个计数器(仅使用“纯”python --> 没有库),它带有countries_nametags 列表,它将在字典中识别它并计算与该country_nametag关联的大陆

例子:

continent_dict = {'BR': 'America','GEO': 'Asia','JP': 'Asia','SWZ': 'Africa','GER':'Europe','SRB': 'Europe','ARG': 'America'}

列表:

countries = ['PT','ARG','GEO','JP','SRB','BR']

continent_counter = {'America':0, 'Asia':0,'Africa':0,'Europe':0,'Oceania':0} #dictionary that stores the number of occurencies
for country in countries:
    continent_counter[continent_nations_dict[country]] = 1
Max_Continent = max(continent_counter, continent_counter.get)

它得到错误......(可能以我获得max_continent 值的方式?

标签: pythonlistdictionarytuplescounter

解决方案


您可以将数组值“映射”为字典中的大陆列表,并使用“max”计算最频繁的大陆

  c_list=list(countries.map(lambda x: continent_dict[x])
  max( set(c_list), key=c_list.count)

推荐阅读