计算布尔情况的数量

问题描述 投票:0回答:1

如果存在两个字段,则对应的字段为布尔值。

  • x_字段
  • y_字段

我想计算当有多个布尔字段时可以出来的案例数量。

例如,如上所述,两个布尔字段总共可以创建 4 种组合。

  • x_field(真),y_field(真)
  • x_field(真),y_field(假)
  • x_field(假),y_field(真)
  • x_field(假),y_field(假)

如果你有一个数组,有两个字段都是布尔类型,你能计算出事例的数量并像这样的形式表达吗?

# 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,
}]

python
1个回答
0
投票

这是解决这个问题的一种方法

# 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}]
© www.soinside.com 2019 - 2024. All rights reserved.