2014-01-16 55 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