如何创建排除某些结果的笛卡尔积?

How to create a cartesian product excluding some results?

为了我的计算,我需要所有由 0 和 1 组成的 32 元素笛卡尔积,其中有 12 个 1。

我目前正在使用以下方法:

for k,l in enumerate(itertools.product([0,1], repeat=32)):
        if l.count(1)==12:                                        
            # rest code

但是如您所见,对于如此大的笛卡尔积来说,它并不是最优的。

如何构建我需要的列表而不必遍历所有元素 itertools.product 并且没有额外的 if 条件?有更快的方法吗?

这只会生成 bits 个元素的列表,其中 ones1,其余是 0:

def binLimit1s( bits, ones, prefix=[] ):
    if bits<ones:
        yield prefix
    elif ones==0:
        yield prefix + [0]*bits
    elif ones==bits:
        yield prefix + [1]*bits
    else:
        for x in binLimit1s( bits-1, ones, prefix+[0] ):
            yield x
        for x in binLimit1s( bits-1, ones-1, prefix+[1] ):
            yield x

在你的情况下,你会使用

binLimit1s( 32, 12 )