我使用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}
试试这个:
输出:
您可以使用
zip
从元组列表中提取国家的名称,然后使用collections.Counter来计算国家名称的频率为了不使用
collections
,我们可以使用字典来收集频率两种情况下的输出都是相同的
使用
defaultdict
:相关问题 更多 >
编程相关推荐