Python中任意深度嵌套字典的值笛卡尔乘积实现方法问询
实现方案
代码实现
import itertools from typing import Any, List, Dict def nested_cartesian(input_data: Any) -> List[Any]: # 处理列表:列表内元素互斥,逐个展开后合并所有可能 if isinstance(input_data, list): result = [] for item in input_data: result.extend(nested_cartesian(item)) return result # 处理字典:所有键需同时存在,对每个值的所有可能做笛卡尔乘积 elif isinstance(input_data, dict): keys = list(input_data.keys()) # 递归获取每个键对应的所有可选值 value_options = [nested_cartesian(input_data[key]) for key in keys] # 做笛卡尔乘积,每个组合拼成新字典 combined = [] for values in itertools.product(*value_options): combined.append(dict(zip(keys, values))) return combined # 基础类型,无分支选择,直接返回单元素列表 else: return [input_data]
调用测试
针对你给出的输入示例,调用方式如下:
d = { "country": [1, 2], "health_state": [ {"healthy": [1]}, {"breast cancer": {"stage": [1, 2]}} ] } output = nested_cartesian(d) # 打印输出结果 for item in output: print(item)
运行后输出结果为:
{'country': 1, 'health_state': {'healthy': 1}} {'country': 2, 'health_state': {'healthy': 1}} {'country': 1, 'health_state': {'breast cancer': {'stage': 1}}} {'country': 1, 'health_state': {'breast cancer': {'stage': 2}}} {'country': 2, 'health_state': {'breast cancer': {'stage': 1}}} {'country': 2, 'health_state': {'breast cancer': {'stage': 2}}}
规则匹配说明
该实现完全满足你提出的两条规则:
- 输入列表中的任意两个元素不会同时出现在输出的单个元素中,列表处理逻辑仅会逐个选取单个元素展开
- 输入字典的所有键都会同时出现在输出的单个元素中,嵌套层级的字典也遵循该逻辑,不会丢失任意层级的键
注:你给出的期望输出示例中的
health state为笔误,实现中默认和输入的health_state键名保持一致,如有需要可自行调整键名映射。
内容的提问来源于stack exchange,提问作者rorance_
相关产品推荐
相关产品推荐

