3

我有一个列表,我想通过在所有可能的位置添加 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 放在开头,将 0 或 1 放在位置 2 给出[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].

有没有聪明的方法来做到这一点?

4

3 回答 3

3

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)])
于 2013-09-24T11:31:51.770 回答
1

我想你想要的是itertools.product

import itertools
x = 2
l = [0, 1]
print list(itertools.product(l + [0, 1], repeat=len(l)+x))
于 2013-09-24T10:26:48.080 回答
1
# input
l=[1,1]
x=1

# create bit combinations that may be added to l
import itertools
combos = itertools.product([0,1], repeat=x)

# iterate through positions (k) and bit combinations (c) with
# a single generator expression. Might be more memory efficient
# if combos would only be generated directly here
set(tuple(l)[:k] + c + tuple(l)[k:] for c in combos for k in range(len(l)+1))

# returns
# set([(0, 1, 1), (1, 1, 1), (1, 1, 0), (1, 0, 1)])
于 2013-09-24T12:01:49.920 回答