从数字列表中创建图案

2024-04-27 04:03:10 发布

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

我有一个元素范围从0到3的列表。我想创建一个列表模式,这样如果有0,我就不会改变任何值,如果有1,我就改变0和1之间的值。如果有一个2,我改变它的值从0,1和2。这听起来可能令人困惑,但简而言之,我想生成这样一个模式:

input_list = [0, 0, 0, 0]
output = [0, 0, 0, 0] # Since input only has 0s we do not permute their values.

input_list = [1,0,0,0]
output = [0,0,0,0], [1,0,0,0] # We can permute the values of the 1 present.

input_list = [1,0,0,1]
output = [0,0,0,0], [1,0,0,0], [0,0,0,1], [1,0,0,1]

在列表包含2的情况下,我们将其值从0-1-2排列

input_list = [2,0,0,0]
output = [0,0,0,0], [1,0,0,0], [2,0,0,0]

input_list = [1,0,0,2]
output = [0,0,0,0], [1,0,0,0], [0,0,0,1], [1,0,0,1], [0,0,0,2], [1,0,0,2]

如果列表中存在3,则显示类似的输出。你知道吗

我有点不确定该如何处理这个问题。任何帮助都会很好。你知道吗

另外,这不是家庭作业问题。我只是在一个研究项目的工作,需要一些模拟类似的模式。复杂性不是一个问题,而是一个低复杂性的解决方案。:D个


Tags: the元素only列表inputoutput模式do
2条回答
from itertools import product
input_list = [1,0,0,2]

list( product(*(range(x+1) for x in input_list)) )

输出:

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

下面是一个可能的解决方案:

input_list = [1, 0, 0, 2]
outputs = []

def get_outputs(input_list):
    if len(input_list) == 0:
        return [[]]
    first = input_list[0]
    outputs = get_outputs(input_list[1:])
    result = [[0] + out for out in outputs]
    if first >= 1:
        result += [[1] + out for out in outputs]
    if first >= 2:
        result += [[2] + out for out in outputs]
    if first == 3:
        result += [[3] + out for out in outputs]
    return result

print(get_outputs(input_list))

解决方案未优化。在大名单上运行可能需要一段时间。如有任何改进或建议,我们将不胜感激。你知道吗

相关问题 更多 >