枚举在python中带有标签的笛卡尔积的最佳方法? [英] Best way to enumerate a cartesian product with labels in python?
本文介绍了枚举在python中带有标签的笛卡尔积的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个将变量映射到可能结果的字典:
{'lblA':[False,True],'lblB':[False,True],'lblC':[0, 1,2]}
Given a dictionary mapping variables to possible outcomes:
{ 'lblA' : [False, True], 'lblB' : [False, True], 'lblC' : [0,1,2] }
我想枚举所有可能的字典结果:
I want to enumerate all possible dictionary outcomes:
[ { 'lblA' : False , 'lblB' : False, 'lblC' : 0 },
{ 'lblA' : True , 'lblB' : False, 'lblC' : 0 },
{ 'lblA' : False , 'lblB' : True, 'lblC' : 0 },
{ 'lblA' : True , 'lblB' : True, 'lblC' : 0 },
{ 'lblA' : False , 'lblB' : False, 'lblC' : 1 },
{ 'lblA' : True , 'lblB' : False, 'lblC' : 1 },
{ 'lblA' : False , 'lblB' : True, 'lblC' : 1 },
{ 'lblA' : True , 'lblB' : True, 'lblC' : 1 },
{ 'lblA' : False , 'lblB' : False, 'lblC' : 2 },
{ 'lblA' : True , 'lblB' : False, 'lblC' : 2 },
{ 'lblA' : False , 'lblB' : True, 'lblC' : 2 },
{ 'lblA' : True , 'lblB' : True, 'lblC' : 2 } ]
我知道这可以递归进行,但是我真的很想用做到itertools
以提高速度。
I know that this could be done recursively, but I'd really like to do it with itertools
for speed.
有人知道这样做的最好方法吗?
Does anyone know the best way to do this?
非常感谢您的帮助!
我想对任意字典进行此操作。
I want to do this for an arbitrary dictionary.
推荐答案
[dict(zip(('lblA', 'lblB', 'lblC'), term)) for term in
itertools.product((False, True) , (False, True), (0, 1, 2))]
编辑:
挑剔,挑剔...
src = {'lblA': (False, True), 'lblB': (False, True), 'lblC': (0, 1, 2)}
labels, terms = zip(*src.items())
print [dict(zip(labels, term)) for term in itertools.product(*terms)]
这篇关于枚举在python中带有标签的笛卡尔积的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文