【问题标题】:How to create a counter without libraries?如何在没有库的情况下创建计数器?
【发布时间】:2021-01-12 22:30:30
【问题描述】:

我想用 国家名称标签列表,它会字典上识别它,并将与该相关联的大陆计数为 strong>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)

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

【问题讨论】:

  • 请从intro tour 重复on topichow to ask。 “告诉我如何解决这个编码问题?”与 Stack Overflow 无关。您必须诚实地尝试解决方案,然后就您的实施提出具体问题。

标签: python list dictionary tuples counter


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    您可以创建一个字典,其中大洲的名称作为键,与每个大洲关联的国家的数量作为值。

    continent_counter = {'America':0, 'Asia':0,'Africa':0,'Europe':0}#,etc...
    for country in countries:
        continent_counter[continent_dict[country]] += 1
    Max_Continent = max(continent_counter, key=continent_counter.get)
    print(Max_Continent)
    

    如果两个大陆相等(与它们相关的国家数量相同且数量最多),则只会将其中一个作为输出。如果你需要这两个大陆,你可以在前面的代码中添加这个:

    All_Continents = [] #Creates the list that will contain all the highest 
                        #ranked continents
    for key, value in continent_counter.items(): #loop over continent_counter
        if value == continent_counter[Max_Continent]: #if we find a max val
            All_Continents.append(key)                # we append the name of the 
                                                      #continent to the list
    print(All_Continents)
    

    【讨论】:

    • 谢谢伙计!正是这个!在看到这个之前我已经发现了代码的第一部分,但是第二部分是一流的!
    猜你喜欢
    • 1970-01-01
    • 2015-09-24
    • 2011-07-13
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 2015-09-22
    • 2017-01-15
    相关资源
    最近更新 更多