生成零和b的所有可能组合

时间:2014-09-20 11:34:42

标签: python numpy combinations itertools

是否有一种有效的方法来生成所有可能的2个1和8个零组合的列表(或数组)? E.g。

[[0,0,0,0,0,0,0,0,1,1],
 [0,0,0,0,0,0,0,1,0,1,],
 ...]

这有效,但可能有更好的方法吗?

import numpy as np
result = []
for subset in itertools.combinations(range(10), 2):
    subset = list(subset)
    c = np.zeros(10)
    c[subset] = 1
    result.append(c)

很想知道如何优化此代码。

3 个答案:

答案 0 :(得分:4)

嗯,它并没有太大的不同,但对Numpy数组进行批量操作肯定会有更少的开销:

import itertools
import numpy

which = numpy.array(list(itertools.combinations(range(10), 2)))
grid = numpy.zeros((len(which), 10), dtype="int8")

# Magic
grid[numpy.arange(len(which))[None].T, which] = 1

grid
#>>> array([[1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
#>>>        [1, 0, 1, 0, 0, 0, 0, 0, 0, 0],
#>>>        [1, 0, 0, 1, 0, 0, 0, 0, 0, 0],
#>>>        [1, 0, 0, 0, 1, 0, 0, 0, 0, 0],
#>>>        [1, 0, 0, 0, 0, 1, 0, 0, 0, 0],
#>>> ...

大部分时间用于numpy.array(list(itertools.combinations(range(10), 2)))。我尝试使用numpy.fromiter,但我没有得到任何速度提升。由于一半的时间实际上是生成元组,因此进一步改进的唯一真正方法是生成C或Cython之类的组合。

答案 1 :(得分:1)

使用numpy.bincount替代方案:

>>> [np.bincount(xs, minlength=10) for xs in itertools.combinations(range(10), 2)]
[array([1, 1, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int64),
 array([1, 0, 1, 0, 0, 0, 0, 0, 0, 0], dtype=int64),
 array([1, 0, 0, 1, 0, 0, 0, 0, 0, 0], dtype=int64),
 array([1, 0, 0, 0, 1, 0, 0, 0, 0, 0], dtype=int64),
 ...]

答案 2 :(得分:0)

我们不应该为此使用排列吗?例如,

from itertools import permutations as perm
a, b = 6, 2
print '\n'.join(sorted([''.join(s) for s in set(t for t in perm(a*'0' + b*'1'))]))