包含(嵌入式)列表理解的词典理解

2024-09-26 18:04:54 发布

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

如何返回每个国家作为键,以及该国的城市列表作为值?使用字典和嵌入式列表理解?不使用集合

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

Tags: city列表字典国家countryspainboschnetherlands
1条回答
网友
1楼 · 发布于 2024-09-26 18:04:54

你可以这样做:

my_dict = {item[0]: [subitem for subkey, subitem in country_city_tuples if subkey == item[0]] for item in country_city_tuples}

输出如下:

{'Netherlands': ['Alkmaar', 'Tilburg', 'Den Bosch', 'Eindhoven'], 'Italy': ['Milano', 'Roma'], 'Spain': ['Madrid', 'Barcelona', 'Cordoba', 'Toledo']}

相关问题 更多 >

    热门问题