如何生成关联嵌套字典的笛卡尔积排列?求简洁实现方案
解决方案
基于原数据结构的实现
因为颜色与物品名称强关联,我们可以先遍历每个物品及其对应的颜色列表,再将颜色与所有类型做笛卡尔积,最终组合成目标字典:
import itertools items = { "item_name": { "apple": {"color": ["red", "blue"]}, "banana": {"color": ["yellow", "red"]} }, "type": ["ripe", "not_ripe"] } result = [] for item_name, details in items["item_name"].items(): # 获取当前物品的所有颜色 colors = details["color"] # 生成颜色和类型的笛卡尔积 for color, item_type in itertools.product(colors, items["type"]): result.append({ "item_name": item_name, "colors": color, "type": item_type }) # 输出结果 print(result)
优化数据结构后的简洁实现
如果允许调整原数据结构,建议将物品与颜色的对应关系整理成更直观的列表形式,这样可以用列表推导式一步完成:
调整后的数据结构
items = { "items": [ {"name": "apple", "colors": ["red", "blue"]}, {"name": "banana", "colors": ["yellow", "red"]} ], "types": ["ripe", "not_ripe"] }
实现代码
import itertools items = { "items": [ {"name": "apple", "colors": ["red", "blue"]}, {"name": "banana", "colors": ["yellow", "red"]} ], "types": ["ripe", "not_ripe"] } result = [ {"item_name": item["name"], "colors": color, "type": item_type} for item in items["items"] for color, item_type in itertools.product(item["colors"], items["types"]) ] print(result)
两种方式都能生成符合要求的笛卡尔积结果,优化后的结构更易维护,代码也更简洁。
内容的提问来源于stack exchange,提问作者bk_
相关产品推荐
相关产品推荐

