python:通过集合的子集为循环创建迭代器

标签 python

我有一个连续整数序列,例如 [1, 2, 3]。我想创建一个遍历该集合所有子集的迭代器。在这种情况下 [], [1],...,[1,2,3]。我怎么能这样做?

最佳答案

itertools documentation包含此构造的配方,名称为 powerset,如果您需要的话。

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

关于python:通过集合的子集为循环创建迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20297154/

相关文章:

python - Osmnx 中给定边缘属性的测量/尺寸单位是什么

Python - Selenium - 打印网页

python - 如何在同一词典下合并两个嵌套词典

python - 在 Dask 数组上使用 scikit-learn cosine_similarity - python

python - 要添加到新列表 Python/Django 中的特定元素排序

python - 使用 numpy.memmap 映射设备文件

python - 如何在没有root权限的情况下在conda中安装pip包?

python - 简单的 Python Pandas EMA (ewma)?

python 请求 |构建 POST 请求体

Python re.findall 与 groupdicts