在嵌套字典中生成所有可能的组合 [英] Generating all possible combinations in a nested dictionary

查看:102
本文介绍了在嵌套字典中生成所有可能的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要测试所有可能的安装配置.配置保存在有时包含嵌套数组的字典数组中.

I need to test all possible installation configurations possible. The configurations are kept in a dictionary array that sometimes contains nested arrays.

以下是配置信息的示例(实际配置要长得多):

Here's a sample of the configuration information (actual configuration is much longer):

config = {'database': 'sqlite',
          'useExisting': False,
          'userCredentials': {'authType': 'windows', 
                              'user': r'.\Testing', 
                              'password': 'testing'
                             }
         }

对于database,选项为['sqlite','mysql','oracle'],对于useExisting,选项为[True, False].我可以弄清楚如何进行所有排列.

For database, options are ['sqlite','mysql','oracle'], and for useExisting, the options are [True, False]. I can figure out how to go through all permutations of those.

但是对于userCredentials,选项可以完全不同.如果authTypedatabase,则需要其他参数.我可以创建一个循环遍历并创建所有有效组合的函数,但是如何加入它们呢?还是有更好的方法来生成配置?

But for userCredentials, the options can be quite different. If authType is database, I need additional parameters. I can create a function that'll loop through and create all valid combinations, but how do I join them? Or is there a better way to generate the configurations?

userCredentials可能也有不同的设置.例如,我有两个用户帐户,testing1和testing2.我需要使用两个用户帐户(最好是使用所有可能的配置)运行测试.我很难弄清楚如何像这样嵌套时递归地生成所有配置.

The userCredentials may also have different settings. For instance, I have two user accounts, testing1 and testing2. I'll need to run the tests with both user accounts, and preferably with all possible configurations. I'm having trouble figuring out how to recursively generate all configurations when it's nested like this.

推荐答案

这是您要找的东西吗?它构建使用 intertools.product .如果authType为'database',它将使用其他参数更新userCredentials.根据需要进行修改:

Is this what you are looking for? It builds all combinations of database, useExisting, and authType listed using intertools.product. If authType is 'database' it updates the userCredentials with additional parameters. Modify as needed:

from itertools import product

def build_config(db,flag,authType,userPass):
    config = dict(database=db,useExisting=flag)
    config['userCredentials'] = {
        'authType': authType, 
        'user': userPass[0], 
        'password': userPass[1]
    }
    if authType == 'database':
        config['userCredentials'].update(
            dict(extra=1,param=2))
    return config

database = ['sqlite','mysql','oracle']
useExisting = [True, False]
authType = ['windows','database']
userPass = [('testing1','pass1'),('testing2','pass2')]

for options in product(database,useExisting,authType,userPass):
    config = build_config(*options)
    print config

这篇关于在嵌套字典中生成所有可能的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆