【问题标题】:Generating dictionaries that are permutations of larger dictionaries生成字典是较大字典的排列
【发布时间】:2018-03-28 02:11:25
【问题描述】:

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

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)

【问题讨论】:

    标签: python python-2.7 dictionary permutation


    【解决方案1】:

    这是使用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}?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2016-12-05
    • 1970-01-01
    相关资源
    最近更新 更多