如何在Python中从列表的dict中的值生成所有组合 [英] How to generate all combination from values in dict of lists in Python
本文介绍了如何在Python中从列表的dict中的值生成所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想生成在dict中索引的列表中的值的所有组合:
I would like to generate all combinations of values which are in lists indexed in a dict:
{'A':['D','E'],'B':['F','G','H'],'C':['I','J']}
每次,每个dict条目中的一项都会被选中,并与其他键中的项组合在一起,所以我有:
Each time, one item of each dict entry would be picked and combined to items from other keys, so I have:
['D','F','I']
['D','F','J']
['D','G','I']
['D','G','J']
['D','H','I']
...
['E','H','J']
我知道在itertools
中有一些东西可以生成列表中项目的组合,但是我不认为我可以在这里使用它,因为我有不同的值池".
I know there is a something to generate combinations of items in list in itertools
but I don't think I can use it here since I have different "pools" of values.
是否有任何现有的解决方案可以执行此操作,或者我应该如何继续执行此操作,我对这种嵌套结构还是很满意.
Is there any existing solution to do this, or how should I proceed to do it myself, I am quite stuck with this nested structure.
推荐答案
import itertools as it
my_dict={'A':['D','E'],'B':['F','G','H'],'C':['I','J']}
allNames = sorted(my_dict)
combinations = it.product(*(my_dict[Name] for Name in allNames))
print(list(combinations))
哪些印刷品:
[('D', 'F', 'I'), ('D', 'F', 'J'), ('D', 'G', 'I'), ('D', 'G', 'J'), ('D', 'H', 'I'), ('D', 'H', 'J'), ('E', 'F', 'I'), ('E', 'F', 'J'), ('E', 'G', 'I'), ('E', 'G', 'J'), ('E', 'H', 'I'), ('E', 'H', 'J')]
这篇关于如何在Python中从列表的dict中的值生成所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文