使用dictionarycomprehension返回country作为键,使用country的城市总数作为值

2024-09-26 18:15:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用dict理解返回国家名称作为唯一键,并希望值为该国的城市数。如何从元组列表中计算城市数?你知道吗

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}


Tags: 名称city列表国家countrydict元组spain
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}

您可以使用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}

使用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})

相关问题 更多 >

    热门问题