首页 > 解决方案 > 如何从给定的集合中找到子集,如下所示

问题描述

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

标签: pythonlistsettuplessubset

解决方案


您可以使用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)

推荐阅读