通过将元素替换为0来生成所有可能的列表

时间:2018-04-30 13:42:19

标签: python python-3.x list combinations

我想从列表中创建所有不同的列表,分别为0,1,2,3 ...所有元素都被其他元素替换 例如,如果替换项为0:

L=[1,2,3]
->[1,2,3],[0,2,3],[1,0,3],[1,2,0],[0,0,3],[0,2,0],[1,0,0],[0,0,0]

到目前为止,我已经尝试过设法做我在使用Itertools时所做的事情,但仅限于将1值替换为0的情况 有谁知道怎么做?

4 个答案:

答案 0 :(得分:6)

每个人都在这里努力。我们希望每个值都是原始值或0 - 我们想要像(1,0),(2,0)和(3,0)这样的对:

>>> from itertools import product, repeat
>>> L = [1, 2, 3]
>>> zip(L, repeat(0))
<zip object at 0x7f931ad1bf08>
>>> list(zip(L, repeat(0)))
[(1, 0), (2, 0), (3, 0)]

然后我们可以将其传递给product

>>> list(product(*zip(L, repeat(0))))
[(1, 2, 3), (1, 2, 0), (1, 0, 3), (1, 0, 0), (0, 2, 3), (0, 2, 0), (0, 0, 3), (0, 0, 0)]

答案 1 :(得分:3)

这是使用itertools的一种方式。这种方法的好处是它很懒惰。

在生成器__next__的每个transformer调用中生成一个新列表。

或者,如下所示,您可以通过在生成器函数上调用list来输出所有组合。

from itertools import combinations, chain

A = [1, 2, 3]

def transformer(x):
    idx = chain.from_iterable(combinations(range(len(x)), i) for i in range(len(x)+1))
    for indices in idx:
        y = x.copy()
        for j in indices:
            y[j] = 0
        yield y

res = list(transformer(A))

print(res)

[[1, 2, 3], [0, 2, 3], [1, 0, 3], [1, 2, 0], [0, 0, 3], [0, 2, 0], [1, 0, 0], [0, 0, 0]]

答案 2 :(得分:1)

您可以使用递归。首先,创建一个可以为输入的每个索引生成完整组合的函数:

def full_combinations(d, current = []):
   if len(d) == len(current):
     yield current
   else:
     yield current
     for i in range(len(d)):
        if len(set(current+[i])) == len(current)+1:
           yield from full_combinations(d, current+[i])

combination_list = list(full_combinations([1, 2, 3]))
new_results = [[0 if c in i else a for c, a in enumerate([1, 2, 3])] for i in combination_list]
full = [a for i, a in enumerate(new_results) if a not in new_results[:i]]

输出:

[[1, 2, 3], [0, 2, 3], [0, 0, 3], [0, 0, 0], [0, 2, 0], [1, 0, 3], [1, 0, 0], [1, 2, 0]]

答案 3 :(得分:-1)

它不漂亮,但我相信你可以让这个想法发挥作用。

我们的想法是使用itertools.combinations来获取每个长度的索引的所有组合,然后我们用itertools.chain()来展平这个列表。

然后我们遍历这个列表列表,将这些索引设置为替换字符。

import itertools
l = [1,2,3]
replace = 0

indices = list(itertools.chain(*[list(itertools.combinations(list(range(len(l))),z+1)) for z in range(len(l))]))

allcombs = [[l]]
for i in indices:
    l2 = l[:]
    for j in i:
        l2[j] = replace
    allcombs.append(l2)

print(allcombs)

[[[1,2,3]],[0,2,3],[1,0,3],[1,2,0],[0,0,3],[0,2 ,0],[1,0,0],[0,0,0]]

相关问题