所有复杂列表的组合

Oph*_*lia 5 python combinatorics

我想找到以下列表的所有可能组合:

data = ['a','b','c','d'] 
Run Code Online (Sandbox Code Playgroud)

我知道这看起来很简单,可以通过以下代码实现:

comb = [c for i in range(1, len(data)+1) for c in combinations(data, i)]
Run Code Online (Sandbox Code Playgroud)

但我想要的实际上是一种给列表数据的每个元素两种可能性('a''-a')的方法.

组合的一个例子可以是['a','b'],['-a','b'],['a','b','-c'],等,而不像当然下面的情况 ['-a','a'].

Kev*_*vin 5

你可以编写一个生成器函数,它接受一个序列并产生每个可能的否定组合.像这样:

import itertools
def negations(seq):
    for prefixes in itertools.product(["", "-"], repeat=len(seq)):
        yield [prefix + value for prefix, value in zip(prefixes, seq)]

print list(negations(["a", "b", "c"]))
Run Code Online (Sandbox Code Playgroud)

结果(为清晰起见修改了空白):

[
    [ 'a',  'b',  'c'], 
    [ 'a',  'b', '-c'], 
    [ 'a', '-b',  'c'], 
    [ 'a', '-b', '-c'],
    ['-a',  'b',  'c'],
    ['-a',  'b', '-c'], 
    ['-a', '-b',  'c'], 
    ['-a', '-b', '-c']
]
Run Code Online (Sandbox Code Playgroud)

您可以使用类似的功能将其集成到现有代码中

comb = [x for i in range(1, len(data)+1) for c in combinations(data, i) for x in negations(c)]
Run Code Online (Sandbox Code Playgroud)