python - 从数字列表创建模式

标签 python algorithm list sequence

我有一个列表,其中的元素范围从 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

最佳答案

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

关于python - 从数字列表创建模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58611086/

相关文章:

python - pandas 使用 float64 的最大小数位数

python - 运行前绘制 Celery canvas

algorithm - 如何初始化 "A Fast Voxel Traversal Algorithm for Ray Tracing"中的 t 变量?

java - 为什么即使提供了初始容量,我们也不能在将元素添加到第 (n-1) 个索引之前将元素添加到列表中的第 n 个索引

python - 在Python中为什么是list[i :i] = [n] insert an element in list[i:i]

c# - 与列表进行快速字符串比较

python - 用具有相似属性的项目的平均值替换属性零值

python - Django 模板 "for loops"无法正常工作

algorithm - 非重叠子区间的区间

java - 水库采样算法