给出这样一本词典,有些条目是元组...
params = {
'a': 'static',
'b': (1, 2),
'c': ('X', 'Y')
}
我需要的项目的"产品"到一个像这样的字典列表,与元组展开,以便在b中的每一项将匹配在c中的每一项…
[{ 'a': 'static', 'b': 1, 'c': 'X' },
{ 'a': 'static', 'b': 1, 'c': 'Y' },
{ 'a': 'static', 'b': 2, 'c': 'X' },
{ 'a': 'static', 'b': 2, 'c': 'Y')}]
我可以很容易地将初始输入分为非元组项和元组项的列表,并在乘法之前将每个元组的键作为"标签"应用于值,因此它们看起来像这样:'b##1', 'b##2', 'c##X', 'c##Y'
.然后在乘法后将它们解析回上面的dict.如果我总是看到2个元组项(如b和c),我可以很容易地将两者都传递给itertools.products
.但可能有0.. n元组项,product()
不会以这种方式乘以列表的列表.有人能想到解决办法吗?
TAG = '##'
# separate tuples and non-tuples from the input, and prepend the key of each tuple as a tag on the value to parse out later
for key, value in params.items():
if type(value) is tuple:
for x in value:
tuples.append(f'{key}{TAG}{x}')
else:
non_tuples.append({key: value})
print(list(product(tuples)) # BUG: doesn't distribute each value of b with each value of c