2014-01-16 49 views
0

您好,我已经看过扔论坛,但没有找到解决我的问题。 问题是: 我怎么能找到所有可能的子集[是长度l]的S大小的列表。 并将其返回到列表中。S的长度列表中的[长度为l]的子集

+1

外观为幂配方在[itertools](http://docs.python.org/2/library/itertools.html)。 – kojiro

+3

['itertools.combinations'](http://docs.python.org/2/library/itertools.html#itertools.combinations) – thefourtheye

+0

我确定这是重复的。 – kkuilla

回答

1
In [162]: x=[1,2,3] 
    ...: from itertools import combinations 
    ...: print [subset for i in range(len(x)+1) for subset in combinations(x, i)] 

#outputs: [(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)] 

做到这一点而不组合

In [237]: import numpy as np 
    ...: x=np.array([1,2,3]) 
    ...: n=2**len(x) 
    ...: res=[] 
    ...: for i in range(0, n): 
    ...:  mask='{0:b}'.format(i).zfill(len(x)) 
    ...:  mask=np.array([int(idx) for idx in mask], bool) 
    ...:  res.append(x[mask].tolist()) 
    ...: print res 
#output: [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] 
+0

谢谢!但是没有组合就有另外一种方法可以做到这一点? – guffi8

+0

@ user3202912,答案已更新 – zhangxaochen