生成作为较大字典排列的字典

2024-04-19 22:20:11 发布

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

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

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)

Tags: test程序标题数量dictionary字典main选项
1条回答
网友
1楼 · 发布于 2024-04-19 22:20:11

这里有一种使用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}]

相关问题 更多 >