我想要一个Python函数
cartesian_product
,它接受列表字典作为输入,并返回一个列表作为输出,其中包含所有可能的字典作为元素,这些字典可以通过从每个列表中获取一个元素来形成。这是一个例子:
打电话
cartesian_product({1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 'f']})
应该回来
[
{1: 'a', 2: 'c', 3: 'e'},
{1: 'a', 2: 'c', 3: 'f'},
{1: 'a', 2: 'd', 3: 'e'},
{1: 'a', 2: 'd', 3: 'f'},
{1: 'b', 2: 'c', 3: 'e'},
{1: 'b', 2: 'c', 3: 'f'},
{1: 'b', 2: 'd', 3: 'e'},
{1: 'b', 2: 'd', 3: 'f'}
]
这应该可以解决问题:
import itertools
def cartesian_product(d):
return [dict(zip(d, p)) for p in itertools.product(*d.values())]
演示:
>>> d = {1: ['a', 'b'], 2: ['c', 'd'], 3: ['e', 'f']}
>>> from pprint import pp
>>> pp(cartesian_product(d))
[{1: 'a', 2: 'c', 3: 'e'},
{1: 'a', 2: 'c', 3: 'f'},
{1: 'a', 2: 'd', 3: 'e'},
{1: 'a', 2: 'd', 3: 'f'},
{1: 'b', 2: 'c', 3: 'e'},
{1: 'b', 2: 'c', 3: 'f'},
{1: 'b', 2: 'd', 3: 'e'},
{1: 'b', 2: 'd', 3: 'f'}]