当一个(或多个)值为未知/通配符时,计算列表的排列数

2024-04-26 03:12:09 发布

您现在位置:Python中文网/ 问答频道 /正文

当一个(或多个)值为未知/通配符时,计算列表的排列数

如果我有一系列的选项,比如说3。每个选项可以是1或0。你知道吗

我可以使用itertools来获得可能的组合。你知道吗

但是,如果其中两个选项是已知的,例如[0, 1, "?"]-如何计算出可能的剩余排列,例如(0, 1, 0), or (0, 1, 1)?你知道吗

我有远远超过3个选项,所以需要一个方法,将规模(并允许更多的未知)

import itertools
from pprint import pprint

input_data = []
for i in range(0,3):
    input_data.append([0,1])

print(input_data)

#get all possible combinations
result = list(itertools.product(*input_data))
print("possible permutations:", len(result))
pprint(result)

输出:

[[0, 1], [0, 1], [0, 1]]
possible permutations: 8
[(0, 0, 0),
 (0, 0, 1),
 (0, 1, 0),
 (0, 1, 1),
 (1, 0, 0),
 (1, 0, 1),
 (1, 1, 0),
 (1, 1, 1)]

编辑: 尝试使用西蒙恩建议的方法- 正在尝试用列表选项替换?。。。你知道吗

如果我有[0, 1, "?", "?"],我如何使用[0, 1]来用0替换"?"的第一个实例,用1替换下一个实例?你知道吗

def gen_options(current):
    unks = current.count("?")
    input_data = []
    for i in range(0, unks):
        input_data.append([0, 1])

    permutatons = list(itertools.product(*input_data))
    options = []
    for perm in permutatons:

        option = [perm if x == "?" else x for x in current]
        options.append(option)
    return options

test = [0, 1, "?", "?"]
options = gen_options(test)
print (options)

给予

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

Tags: 方法in列表forinputdata选项result
2条回答

我想itertools.product会做你需要的一切

>>> from itertools import product
>>> x = [0,"?",1,1,0,"?","?"]
>>> a = [(0,1) if e == '?' else (e,) for e in x]
>>> print(a)
[(0,), (0, 1), (1,), (1,), (0,), (0, 1), (0, 1)]
>>> for v in product(*a): 
...    print(v)
...
(0, 0, 1, 1, 0, 0, 0)
(0, 0, 1, 1, 0, 0, 1)
(0, 0, 1, 1, 0, 1, 0)
(0, 0, 1, 1, 0, 1, 1)
(0, 1, 1, 1, 0, 0, 0)
(0, 1, 1, 1, 0, 0, 1)
(0, 1, 1, 1, 0, 1, 0)
(0, 1, 1, 1, 0, 1, 1)

如果你知道一些选项,那么你只需要计算出未知选项的排列。所以如果你有[0,"?",1,1,0,"?","?"],你只需要生成三个值的所有可能的排列,然后插入它们来代替?角色。所以在这种情况下,会有八个选项,其中三个?替换为您在问题中提供的排列。你知道吗

编辑:这里有一些代码

import itertools
from copy import copy

inp=[1,"?",1,"?",0]
output=[]

for p in itertools.product([0,1], repeat=inp.count("?")):
    working = copy(inp)
    p_list=list(p)
    for i, x in enumerate(working):
        if x == "?":
            working[i] = p_list.pop()
    output.append(working)
print(output)

相关问题 更多 >