开发者

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

开发者 https://www.devze.com 2023-01-28 09:59 出处:网络
Given a dictionary mapping variables to possible outcomes: { \'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' : 开发者_如何学C2 },
{ '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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号