如何在字典中生成所有可能的组合

Posted

技术标签:

【中文标题】如何在字典中生成所有可能的组合【英文标题】: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")

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

【问题讨论】:

【参考方案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()]

【讨论】:

以上是关于如何在字典中生成所有可能的组合的主要内容,如果未能解决你的问题,请参考以下文章