gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:50:35 26 4
gpt4 key购买 nike

我有一个连续整数序列,例如 [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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com