If two fields exist, the corresponding fields are Boolean values.
I want to generate all cases that can be represented as a combination of multiple Boolean values.
For example, there are a total of 4 combinations that can be expressed by two Boolean fields as above.
If you have an array with two fields that are Boolean type, can you generate all cases and express like this form?
# before calculate ...
fields = ["x_field", "y_field"]
# after calculate ...
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},]
My Attempted
I thought I could solve this problem with the itertools module, but I wasn't sure which function to use.
I tried to implement using various itertools module functions, but it failed.
from itertools import combinations, permutations
boolean_fields = ["x_field", "y_field"]
# -->
boolean_fields = [True, False, True, False]
x = list(combination(boolean_fields, 2))
I'm surprised no one has proposed this simple one-liner yet...
from itertools import product
fields = ['x', 'y', 'z']
[dict(zip(fields, values)) for values in product([True,False], repeat=len(fields))]
Output:
[{'x': True, 'y': True, 'z': True},
{'x': True, 'y': True, 'z': False},
{'x': True, 'y': False, 'z': True},
{'x': True, 'y': False, 'z': False},
{'x': False, 'y': True, 'z': True},
{'x': False, 'y': True, 'z': False},
{'x': False, 'y': False, 'z': True},
{'x': False, 'y': False, 'z': False}]
Explanation:
product([True,False], repeat=len(fields))
creates all the 2**len(fields)
combinations of True
or False
values.
Then iterating over these combinations, zip(fields, values)
pairs up every field name to its corresponding value.
Finally turn every such pairing into a dict
, and turn that into a list of dicts as you iterate over all the combinations (through list comprehension syntax).