我需要测试所有可能的安装配置。配置保存在字典数组中,有时包含嵌套数组。
这是配置信息的示例(实际配置要长得多):
config = {'database': 'sqlite',
'useExisting': False,
'userCredentials': {'authType': 'windows',
'user': r'.\Testing',
'password': 'testing'
}
}
对于 database
,选项为 ['sqlite','mysql','oracle']
,对于 useExisting
,选项为[对,错]
。我可以弄清楚如何完成这些排列的所有排列。
但是对于userCredentials
,选项可能完全不同。如果authType
是database
,我需要额外的参数。我可以创建一个函数来循环并创建所有有效的组合,但如何加入它们?或者有更好的方法来生成配置吗?
userCredentials
也可能有不同的设置。例如,我有两个用户帐户,testing1 和testing2。我需要使用两个用户帐户运行测试,最好使用所有可能的配置。当像这样嵌套时,我无法弄清楚如何递归生成所有配置。
最佳答案
这是您要找的吗?它构建使用 intertools.product 列出的数据库、useExisting 和 authType 的所有组合。 。如果 authType 是“database”,它将使用附加参数更新 userCredentials。根据需要修改:
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
关于python - 生成嵌套字典中所有可能的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12178291/