30秒学会 Python 片段 · 2023年10月29日

30秒学会 Python 片段 – Powerset

Returns the powerset of a given iterable.

  • Use list() to convert the given value to a list.
  • Use range() and itertools.combinations() to create a generator that returns all subsets.
  • Use itertools.chain.from_iterable() and list() to consume the generator and return a list.

代码实现

from itertools import chain, combinations

def powerset(iterable):
  s = list(iterable)
  return list(chain.from_iterable(combinations(s, r) for r in range(len(s)+1)))

使用样例

powerset([1, 2]) # [(), (1,), (2,), (1, 2)]

翻译自:https://www.30secondsofcode.org/python/s/powerset