Best way to enumerate a cartesian product with labels in python?

限于喜欢 提交于 2019-12-12 09:01:49

问题


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 } ]

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?

Thanks a lot for your help!

Edit

I want to do this for an arbitrary dictionary.


回答1:


[dict(zip(('lblA', 'lblB', 'lblC'), term)) for term in
  itertools.product((False, True) , (False, True), (0, 1, 2))]

EDIT:

Picky, picky...

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)]


来源:https://stackoverflow.com/questions/4299927/best-way-to-enumerate-a-cartesian-product-with-labels-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!