import json
import itertools
import yaml
def flatten(data):
# 将重复的值合并成一个元素
flat_data = []
for key, values in data.items():
if values:
flat_values = set()
for value in values:
if isinstance(value, list):
flat_values |= set(value)
else:
flat_values.add(value)
for flat_value in flat_values:
flat_data.append((key, flat_value))
else:
flat_data.append((key, None))
return dict(flat_data)
def generate_combinations(data, output_prefix):
# 将每个 key 对应的 value 列表转换为集合
data = {k: set(v) for k, v in data.items() if v}
if not data:
return
# 将重复的值合并成一个元素
flat_data = flatten(data)
for key, value in flat_data.items():
if value is None:
continue
# 列出所有要组合的键
other_keys = [k for k in flat_data if k != key and k in data]
if not other_keys:
# 如果只有一个键有值,直接输出这个键和值的组合
output_file = output_prefix + f"{key}_{value}.json"
with open(output_file, "w") as f:
json.dump({key: value}, f, indent=4)
continue
# 列出其他键对应的值的笛卡尔积
other_values = itertools.product(*[data[k] for k in other_keys])
# 遍历当前键对应的所有值
if isinstance(value, list):
for v in value:
# 构造当前键和值的字典
current = {key: v}
# 遍历其他键对应的所有值的笛卡尔积
for other_value in other_values:
# 将其他键和值的字典合并到当前字典中
current.update(dict(zip(other_keys, other_value)))
# 构造输出文件名
output_file = output_prefix + "_".join([f"{k}_{v}" for k, v in current.items()]) + ".json"
# 将当前字典写入到输出文件中
with open(output_file, "w") as f:
json.dump(current, f, indent=4)
else:
# 构造当前键和值的字典
current = {key: value}
# 遍历其他键对应的所有值的笛卡尔积
for other_value in other_values:
# 将其他键和值的字典合并到当前字典中
current.update(dict(zip(other_keys, other_value)))
# 构造输出文件名 output_file = output_prefix + "_".join([f"{k}_{v}" for k, v in current.items()]) + ".json
yaml文件
name:
- Alice
- Bob
age:
- 20
- 21
city:
- Beijing
- Shanghai