[英]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.