简体   繁体   English

从单个值列表中生成所有可能的值组合

[英]Generating all possibles combinations of values from a list of single values

Basically, I want to generate truth table list of values using Python.基本上,我想使用 Python 生成值的真值表列表。 For instance, if I have the following values: [0, 1], I want the following list to be generated:例如,如果我有以下值:[0, 1],我希望生成以下列表:

[(0, 0), (0, 1), (1, 0), (1, 1)] [(0, 0), (0, 1), (1, 0), (1, 1)]

If I want my table to have three inputs, then the following list should be generated:如果我希望我的表有三个输入,那么应该生成以下列表:

[(0, 0, 1), (0, 1, 0), (0, 0, 1), (0, 1, 1), (1, 0, 1), (1, 1, 0), (1, 0, 1), (1, 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)]

So:所以:

  • All permutations should be generated应生成所有排列
  • No duplicate permutation in the list列表中没有重复排列

Right now my solution is the following but I find it heavy:现在我的解决方案如下,但我发现它很重:

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))))

Do you have a better solution ?你有更好的解决方案吗? Such as a one-liner function call比如单行函数调用

It seems like product is enough:看起来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)

does this work?这行得通吗?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM