【问题标题】:How to generate all possible combinations in a dictionary in a dictionary如何在字典中生成所有可能的组合
【发布时间】:2022-01-24 03:02:39
【问题描述】:

所以我在这样的字典中有一个字典:

{'d': {'c': 3}, 'c': {'d': 3, 'b': 2}, 'b': {'c': 2, 'a': 1}, 'a': {'b': 1}}

我需要 python 代码来给出输出:

("d","c")
("c","d")
("c","b")
("b","c")
("b","a")
("a","b")

我不知道该怎么做,我们接受任何帮助。

【问题讨论】:

    标签: python dictionary combinations


    【解决方案1】:
    x = {'d': {'c': 3}, 'c': {'d': 3, 'b': 2}, 'b': {'c': 2, 'a': 1}, 'a': {'b': 1}}
    
    for i in x.keys():
      for j in x.get(i).keys():
        print((i,j))
    

    【讨论】:

      【解决方案2】:

      您可以将列表推导与dict.items 一起使用:

      dct = {'d': {'c': 3}, 'c': {'d': 3, 'b': 2}, 'b': {'c': 2, 'a': 1}, 'a': {'b': 1}}
      
      output = [(key_1, key_2) for key_1, subdct in dct.items() for key_2 in subdct]
      print(output) # [('d', 'c'), ('c', 'd'), ('c', 'b'), ('b', 'c'), ('b', 'a'), ('a', 'b')]
      

      【讨论】:

      • 这正是我想要的。非常感谢您的回答
      【解决方案3】:
      dict1 = {'d': {'c': 3}, 'c': {'d': 3, 'b': 2}, 'b': {'c': 2, 'a': 1}, 'a': {'b': 1}}
      
      [(k1,k2) for k1 in dict1.keys() for k2 in dict1[k1].keys()]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多