【问题标题】:how to find subsets from given sets like below如何从给定的集合中找到子集,如下所示
【发布时间】:2020-09-25 05:33:25
【问题描述】:

如果给定列表是 [1,2,3] 并且输出应该是 [[1], [2], [3], [1,2], [2,3],如何制作获取子集的程序, [1,3],[1,2,3]]。那是如何得到所有可能的组合?

【问题讨论】:

标签: python list set tuples subset


【解决方案1】:

您可以使用itertools.combinations 实现此目的

import itertools

arr = [1, 2, 3] 
res = []

for i in range(len(arr)):
  combinations = itertools.combinations(arr, i + 1)
  for c in combinations:
    res.append(list(c))

print(res)

【讨论】:

    【解决方案2】:

    这是另一种方法不使用 Itertools.combination。

    l=[1,2,3]
    all_comb=[]
    x=len(l)
    for i in range(1,1 << x):
        all_comb.append([l[j] for j in range(x) if (i & (1 << j))])
    all_comb
    

    输出:

    [[1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
    

    【讨论】:

      【解决方案3】:

      在这里你可以试试这个:(inList 是你的输入列表,outList 是你的输出列表)

      import itertools
      outList = []
      
      def subs(S, m):
          return set(itertools.combinations(S, m))
      
      outList = []
      for i in range(0, len(inList),1):
          outList += subs(inList, i)
      

      【讨论】:

        【解决方案4】:

        如果不想使用itertools.combinations,也可以通过纯python代码实现;

        nums=[1,2,3]
        sublist=[]
        for i in range (len(nums)+1):
            for j in range(i+1,len(nums)+1):
                sub=nums[i:j]
                sublist.append(sub)
        print(sublist)
        

        【讨论】:

          【解决方案5】:
          import itertools
          
          input_set = [1, 2, 3]
          subsets = []
          
          for i in range(len(input_set)+1):
              combinations = itertools.combinations(input_set, i)
              for c in combinations:
                  subsets.append(list(c))
          
          print(subsets)
          

          【讨论】:

          • 代码简单易懂,包含空集
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-07
          • 1970-01-01
          • 2023-03-19
          相关资源
          最近更新 更多