【问题标题】:python, split dictionary into list of tuplepython,将字典拆分为元组列表
【发布时间】:2022-01-12 11:11:57
【问题描述】:
dictionary = {1: ['a', 'b'], 2: ['a'], 3: ['b', 'c']}

我希望这本字典在这样的元组列表中: 输出:

[(1, 'a'),(1, 'b'),(2, 'a'),(3, 'b'),(3, 'c')]

请帮帮我!!!

【问题讨论】:

    标签: python list dictionary tuples


    【解决方案1】:

    你可以通过理解来做到这一点:

    [(x, z) for x, y in dictionary.items() for z in y]
    

    或展开:

    out = []
    for x, y in dictionary.items():
        for z in y:
            out.append((x, z))
    

    【讨论】:

      【解决方案2】:

      字典 = {1: ['a', 'b'], 2: ['a'], 3: ['b', 'c']}

      list_of_tuples = []
      for k,v_list in dictionary.items():
          for v in v_list:
              list_of_tuples.append((k,v))
      list_of_tuples
      

      【讨论】:

      • 这不会将列表值“解包”到新的元组中。
      • 感谢@match,已修复
      猜你喜欢
      • 2019-11-24
      • 1970-01-01
      • 2018-10-06
      • 2010-12-19
      • 1970-01-01
      • 2017-04-25
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多