获取Python中所有可能的dict配置的列表 [英] Get list of all possible dict configs in Python

查看:121
本文介绍了获取Python中所有可能的dict配置的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个dict可以描述可能的配置值,例如

  {'a':[1,2],'b':[3,4,5]} 

我想生成所有可接受的配置的列表,例如

  [{'a':1,'b':3},
{'a' 'b':4},
{'a':1,'b':5},
{'a':2,'b':3},
{'a ':2,'b':4},
{'a':1,'b':5}]

我已经看过文档和SO,它似乎涉及 itertools.product ,但是我无法得到它,而不是嵌套for循环

解决方案

您不需要嵌套 for 这里:

  from itertools import product 
[dict(zip(d.keys(),combo))在产品(* d.values())]

产品(* d .values())生成所需的值组合, dict(zip(d.keys(),combo))将每个组合与



演示:

 >>>来自itertools import product 
>>>> d = {'a':[1,2],'b':[3,4,5]}
>>>列表(product(* d.values()))
[(1,3),(1,4),(1,5),(2,3),(2,4) 5)]
>>>产品中的组合(* d.values())]中的[dict(zip(d.keys(),combo))]
[{'a':1,'b':3},{'a' :1,'b':4},{'a':1,'b':5},{'a':2,'b':3},{'a':2,'b' },{'a':2,'b':5}]
>>>来自pprint import pprint
>>>>打印(_)
[{'a':1,'b':3},
{'a':1,'b':4},
{'a' 1,'b':5},
{'a':2,'b':3},
{'a':2,'b':4},
{ 'a':2,'b':5}]


I have dict that describes possible config values, e.g.

{'a':[1,2], 'b':[3,4,5]} 

I want to generate list of all acceptable configs, e.g.

[{'a':1, 'b':3},
 {'a':1, 'b':4},
 {'a':1, 'b':5},
 {'a':2, 'b':3},
 {'a':2, 'b':4},
 {'a':1, 'b':5}]

I've looked through the docs and SO and it certainly seems to involve itertools.product, but I can't get it without a nested for loop.

解决方案

You don't need a nested for loop here:

from itertools import product
[dict(zip(d.keys(), combo)) for combo in product(*d.values())]

product(*d.values()) produces your required value combinations, and dict(zip(d.keys(), combo)) recombines each combination with the keys again.

Demo:

>>> from itertools import product
>>> d = {'a':[1,2], 'b':[3,4,5]} 
>>> list(product(*d.values()))
[(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)]
>>> [dict(zip(d.keys(), combo)) for combo in product(*d.values())]
[{'a': 1, 'b': 3}, {'a': 1, 'b': 4}, {'a': 1, 'b': 5}, {'a': 2, 'b': 3}, {'a': 2, 'b': 4}, {'a': 2, 'b': 5}]
>>> from pprint import pprint
>>> pprint(_)
[{'a': 1, 'b': 3},
 {'a': 1, 'b': 4},
 {'a': 1, 'b': 5},
 {'a': 2, 'b': 3},
 {'a': 2, 'b': 4},
 {'a': 2, 'b': 5}]

这篇关于获取Python中所有可能的dict配置的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆