【问题标题】:subsets [that are of length l] of list in S size [closed]S 大小的列表的子集 [长度为 l] [关闭]
【发布时间】:2014-01-16 14:36:42
【问题描述】:

嗨,我已经看过论坛了,但没有找到解决我问题的方法。 问题是 : 我怎样才能找到 S 大小的列表的所有可能子集[长度为 l]。 并以列表的形式返回。

【问题讨论】:

标签: python python-3.x combinations powerset


【解决方案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]]

【讨论】:

  • 谢谢!但是还有另一种不用组合的方法吗?
  • @user3202912,答案已更新
猜你喜欢
  • 2012-11-15
  • 2011-12-13
  • 2021-09-29
  • 1970-01-01
  • 2017-04-17
  • 2016-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多