我使用的是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}
答案 0 :(得分:3)
您可以使用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}
答案 1 :(得分: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})
答案 2 :(得分:1)
尝试一下:
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}
答案 3 :(得分:1)
将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
答案 4 :(得分:0)
不使用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}