【问题标题】:Dictionary comprehension that contains an (embedded) list comprehension包含(嵌入式)列表理解的字典理解
【发布时间】:2019-10-10 00:15:56
【问题描述】:

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

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

【问题讨论】:

  • 发布你的尝试。我们不是来做你的功课的。

标签: python list tuples list-comprehension dictionary-comprehension


【解决方案1】:

你可以这样做:

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']}

【讨论】:

    猜你喜欢
    • 2016-11-23
    • 2021-02-23
    • 2018-08-04
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    • 2021-12-22
    相关资源
    最近更新 更多