如果存在两个字段,则对应的字段为布尔值。
我想计算当有多个布尔字段时可以出来的案例数量。
例如,如上所述,两个布尔字段总共可以创建 4 种组合。
如果你有一个数组,有两个字段都是布尔类型,你能计算出事例的数量并像这样的形式表达吗?
# before calculate ...
fields = ["x_field", "y_field"]
# after calculate ...
fields = [{
"x_field": True, "y_field": True,
"x_field": True, "y_field": False,
"x_field": False, "y_field": True,
"x_field": False, "y_field": False,
}]
这是解决这个问题的一种方法
# if you're in a python version without type hints,
# use `def combinations(fields):` instead
def combinations(fields: list[str]) -> list[dict[str, bool]]:
out = []
for field in fields:
partials = out
out = []
if partials:
# make new entries with the new field as True or False.
# we need two lists, since modifying a list while
# we're iterating through it leads to issues
for entry in partials:
out.append({**entry, field: True})
out.append({**entry, field: False})
else:
# base care for empty list
out.append({field: True})
out.append({field: False})
return out
fields = ["x_field", "y_field"]
print(combinations(fields))
输出
[{'x_field': True, 'y_field': True},
{'x_field': True, 'y_field': False},
{'x_field': False, 'y_field': True},
{'x_field': False, 'y_field': False}]