首页 > 解决方案 > 当一个(或多个)值未知/通配符时计算出列表的排列数量

问题描述

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

如果我有一系列选项,例如在这里说 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)]

编辑:尝试使用 SimonN 建议的方法 - 尝试?用列表选项替换 ...

如果我有[0, 1, "?", "?"],我如何使用[0, 1]替换 a 的第一个实例"?"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)]]

标签: pythonitertools

解决方案


如果你知道一些选项,那么你只需要计算出未知选项的排列。因此,如果您有[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)

推荐阅读