[英]Generating all possibles combinations of values from a list of single values
基本上,我想使用 Python 生成值的真值表列表。 例如,如果我有以下值:[0, 1],我希望生成以下列表:
[(0, 0), (0, 1), (1, 0), (1, 1)]
如果我希望我的表有三个输入,那么应该生成以下列表:
[(0, 0, 1), (0, 1, 0), (0, 0, 1), (0, 1, 1), (1, 0, 1), (1, 1, 0), ( 1, 0, 1), (1, 1, 1)]
所以:
现在我的解决方案如下,但我发现它很重:
from itertools import permutations
number_of_inputs = 3
set_of_values = [0, 1]
list_of_permutations = list(dict.fromkeys(list(permutations(set_of_values * number_of_inputs, number_of_inputs))))
你有更好的解决方案吗? 比如单行函数调用
看起来product
就足够了:
number_of_inputs = 3
set_of_values = [0, 1]
list_of_permutations = itertools.product(set_of_values, repeat=3)
print(*list_of_permutations)
# (0, 0, 0) (0, 0, 1) (0, 1, 0) (0, 1, 1) (1, 0, 0) (1, 0, 1) (1, 1, 0) (1, 1, 1)
这行得通吗?
from itertools import permutations
number_of_inputs = 3
set_of_values = [0, 1]
result = set(permutations(set_of_values * number_of_inputs, number_of_inputs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.