获取Python中所有可能dict配置的列表

2024-03-29 08:18:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

我已经浏览了文档,当然它似乎涉及itertools.product,但是如果没有嵌套的for循环,我就无法得到它。你知道吗


Tags: 文档列表forproductdictitertools
2条回答

这里不需要嵌套的for循环:

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

product(*d.values())生成所需的值组合,dict(zip(d.keys(), combo))再次将每个组合与键重新组合。你知道吗

演示:

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

您也可以尝试以下方法:

>>> dt={'a':[1,2], 'b':[3,4,5]} 
>>> [{'a':i,'b':j} for i in dt['a'] for j in dt['b']]
[{'a': 1, 'b': 3}, {'a': 1, 'b': 4}, {'a': 1, 'b': 5}, {'a': 2, 'b': 3}, {'a': 2, 'b': 4}, {'a': 2, 'b': 5}]

相关问题 更多 >