【问题标题】:Use a dictionary-comprehension to return country as key and a total number of cities for country as value使用字典理解返回国家作为键和国家的城市总数作为值
【发布时间】:2019-10-08 18:15:18
【问题描述】:

我正在使用 dict-comprehension 将国家/地区名称作为唯一键返回,并希望值为该国家/地区的城市数量。如何计算元组列表中的城市数量?

country_city_tuples= [('Netherlands', 'Alkmaar'),
                      ('Netherlands', 'Tilburg'),
                      ('Netherlands', 'Den Bosch'),
                      ('Netherlands', 'Eindhoven'),
                      ('Spain', 'Madrid'),
                      ('Spain', 'Barcelona'),
                      ('Spain', 'Cordoba'),
                      ('Spain', 'Toledo'),
                      ('Italy', 'Milano'),
                      ('Italy', 'Roma')]

country_names = { 

}

预期结果为:{'Italy': 2 , 'Netherlands': 4, 'Spain': 4}

【问题讨论】:

  • “我正在使用 dict-comprehension 来返回国家/地区名称”——它在哪里?

标签: python tuples dictionary-comprehension


【解决方案1】:

您可以使用zip从元组列表中提取国家名称,然后使用collections.Counter对抗国家名称的频率

from collections import Counter

country_city_tuples= [('Netherlands', 'Alkmaar'),
                      ('Netherlands', 'Tilburg'),
                      ('Netherlands', 'Den Bosch'),
                      ('Netherlands', 'Eindhoven'),
                      ('Spain', 'Madrid'),
                      ('Spain', 'Barcelona'),
                      ('Spain', 'Cordoba'),
                      ('Spain', 'Toledo'),
                      ('Italy', 'Milano'),
                      ('Italy', 'Roma')]

#Extract out country names using zip and list unpacking
country_names, _ = zip(*country_city_tuples)

#Count the number of countries using Counter
print(dict(Counter(country_names)))

不使用collections,我们可以使用字典来收集频率

country_city_tuples= [('Netherlands', 'Alkmaar'),
                      ('Netherlands', 'Tilburg'),
                      ('Netherlands', 'Den Bosch'),
                      ('Netherlands', 'Eindhoven'),
                      ('Spain', 'Madrid'),
                      ('Spain', 'Barcelona'),
                      ('Spain', 'Cordoba'),
                      ('Spain', 'Toledo'),
                      ('Italy', 'Milano'),
                      ('Italy', 'Roma')]

#Extract out country names using zip and list unpacking
country_names, _ = zip(*country_city_tuples)

result = {}

#Count each country
for name in country_names:
    result.setdefault(name,0)
    result[name] += 1

print(result)

两种情况下的输出都是一样的

{'Netherlands': 4, 'Spain': 4, 'Italy': 2}

【讨论】:

    【解决方案2】:

    使用defaultdict

    from collections import defaultdict
    
    country_names  = defaultdict(int)
    for i in country_city_tuples:
        country_names[i[0]]+=1
    
    country_names
    defaultdict(int, {'Netherlands': 4, 'Spain': 4, 'Italy': 2})
    

    【讨论】:

      【解决方案3】:

      试试这个:

      l = set(i[0] for i in country_city_tuples)
      d = {}
      for i in l:
         d[i] = sum([1 for j in country_city_tuples if j[0]==i])
      

      输出

      {'Italy': 2, 'Netherlands': 4, 'Spain': 4}
      

      【讨论】:

        【解决方案4】:

        使用带有生成器的sum,如果国家名称与正在检查的国家/地区匹配,则返回 1,否则返回 0:

        {name: sum(1 if c[0] == name else 0
                   for c in country_city_tuples)
         for name in set(c[0] for c in country_city_tuples)}
        

        你也可以使用dict.get:

        r = {}
        for name, city in country_city_tuples:
            r.get(name, 0) += 1
        

        【讨论】:

          【解决方案5】:

          不使用defaultdict和其他模块

          country_city_tuples= [('Netherlands', 'Alkmaar'),
                                ('Netherlands', 'Tilburg'),
                                ('Netherlands', 'Den Bosch'),
                                ('Netherlands', 'Eindhoven'),
                                ('Spain', 'Madrid'),
                                ('Spain', 'Barcelona'),
                                ('Spain', 'Cordoba'),
                                ('Spain', 'Toledo'),
                                ('Italy', 'Milano'),
                                ('Italy', 'Roma')]
          
          country_names ={}
          for i in country_city_tuples:
              try:
                  if country_names[i[0]]:
                      country_names[i[0]]+=1
              except:
                  country_names[i[0]]=1
          print(country_names)
          
          #output {'Netherlands': 4, 'Spain': 4, 'Italy': 2}
          

          【讨论】:

            猜你喜欢
            • 2014-09-08
            • 2022-06-15
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-12-17
            • 1970-01-01
            • 2017-10-20
            相关资源
            最近更新 更多