如何基于布尔字段列表生成所有布尔值组合?
布尔字段全组合生成方案
需求说明
给定布尔字段名称数组(如fields = ["x_field", "y_field"]),需要生成所有布尔值组合的字典列表。比如两个字段对应4种组合,最终结果格式如下:
result = [{"x_field": True, "y_field": True}, {"x_field": True, "y_field": False}, {"x_field": False, "y_field": True}, {"x_field": False, "y_field": False},]
错误尝试示例
之前误用itertools的combinations/permutations函数,错误代码如下:
from itertools import combinations, permutations boolean_fields = ["x_field", "y_field"] boolean_fields = [True, False, True, False] x = list(combination(boolean_fields, 2)) # 函数名拼写错误+逻辑错误
正确实现方法
需使用itertools.product函数,它专门用于生成多个可迭代对象的笛卡尔积,完美匹配每个字段取True/False的全组合场景。
完整代码
from itertools import product fields = ["x_field", "y_field"] # 生成对应字段数量的布尔值笛卡尔积 boolean_tuples = product([True, False], repeat=len(fields)) # 将每个元组转换为字段名与布尔值对应的字典 result = [dict(zip(fields, combo)) for combo in boolean_tuples] # 验证输出 print(result)
运行结果
[{'x_field': True, 'y_field': True}, {'x_field': True, 'y_field': False}, {'x_field': False, 'y_field': True}, {'x_field': False, 'y_field': False}]
逻辑说明
product([True, False], repeat=len(fields)):根据字段数量,重复生成[True, False]的笛卡尔积。比如2个字段时,会输出4组元组:(True, True), (True, False), (False, True), (False, False)dict(zip(fields, combo)):将每组元组与字段名一一配对,转换成需求中的字典格式
内容的提问来源于stack exchange,提问作者Antoliny Lee
相关产品推荐
相关产品推荐

