我有一个列表,我想通过在所有可能的位置添加 x 1 和 0 来使所有列表成为可能。例如,假设 x = 2 和
l=[0,1]
首先,我们将所有可能的长度为 2 的列表放在开头,给出 [0,0,0,1]
, [0,1,0,1]
, [1,0,0,1]
, [1,1,0,1]
。然后我们在开头放置 0 或 1,在位置 2 放置 0 或 1,给出 [0,0,0,1]
, [0,0,1,1]
, [1,0,0,1]
, [1,0,1,1]
。
然后我们将对列表中可以插入两位的每对可能位置执行相同的操作。当然会有很多重复项,但我可以使用 set
删除它们。
另一个例子,这次 x = 1
l=[1,1]
完整的输出应该是[0,1,1], [1,0,1], [1,1,0], [1,1,1]
。
有没有聪明的方法来做到这一点?
最佳答案
IIUC,你可以使用这样的东西:
from itertools import product, combinations
def all_fill(source, num):
output_len = len(source) + num
for where in combinations(range(output_len), len(source)):
# start with every possibility
poss = [[0,1]] * output_len
# impose the source list
for w, s in zip(where, source):
poss[w] = [s]
# yield every remaining possibility
for tup in product(*poss):
yield tup
给出
>>> set(all_fill([1,1], 1))
set([(0, 1, 1), (1, 1, 0), (1, 1, 1), (1, 0, 1)])
>>> set(all_fill([0,1], 2))
set([(1, 0, 1, 1), (1, 1, 0, 1), (1, 0, 1, 0), (0, 1, 1, 1),
(0, 1, 0, 1), (1, 0, 0, 1), (0, 0, 1, 0), (0, 1, 1, 0),
(0, 1, 0, 0), (0, 0, 1, 1), (0, 0, 0, 1)])
关于python - 在所有可能的地方添加位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18978986/