Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 生成作为较大词典排列的词典_Python_Python 2.7_Dictionary_Permutation - Fatal编程技术网

Python 生成作为较大词典排列的词典

Python 生成作为较大词典排列的词典,python,python-2.7,dictionary,permutation,Python,Python 2.7,Dictionary,Permutation,我不知道我给的标题是否能很好地解释我需要我的程序做什么。我将有以下形式的词典: main_dictionary = {1: [ [a], [b], [c], ... ], 2: [ [a], [b], [c], ... ] , ... } 字典可以任意长,每个键有任意数量的选项。我需要程序来测试这本字典的每一个排列 sub_dictionary = {1: [a], 2: [a], ... } test_program(sub_dictionary) sub_dictionary = {1

我不知道我给的标题是否能很好地解释我需要我的程序做什么。我将有以下形式的词典:

main_dictionary = {1: [ [a], [b], [c], ... ], 2: [ [a], [b], [c], ... ] , ... }
字典可以任意长,每个键有任意数量的选项。我需要程序来测试这本字典的每一个排列

sub_dictionary = {1: [a], 2: [a], ... }

test_program(sub_dictionary)

sub_dictionary = {1: [a], 2: [b], ... }

test_program(sub_dictionary)

下面是使用
itertools.product
的一种方法。结果是“子词典”列表

为简单起见,我使用了一个整数列表作为值,但这可以由您选择的值替换

from itertools import product

d = {1: [3, 4, 5], 2: [6, 7, 8]}

values = list(zip(*sorted(d.items())))[1]

res = [dict(enumerate(x, 1)) for x in product(*values)]
如果需要单独测试每个字典,请改用生成器表达式并对其进行迭代:

for item in (dict(enumerate(x, 1)) for x in product(*values)):
    ...
如果您有字符串键:

res = [dict(zip(sorted(d), x)) for x in product(*values)]
结果:

[{1: 3, 2: 6},
 {1: 3, 2: 7},
 {1: 3, 2: 8},
 {1: 4, 2: 6},
 {1: 4, 2: 7},
 {1: 4, 2: 8},
 {1: 5, 2: 6},
 {1: 5, 2: 7},
 {1: 5, 2: 8}]

我应该指定,键是特定的名称。我如何调整它以获得:{key1:3,key2:6}?