使用itertools的Python中的powerset

2024-06-15 08:29:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Python 3中创建一个powerset。我找到了对itertools的引用 模块,我使用了该页上提供的powerset代码。问题是:代码返回对itertools.chain对象的引用,而我希望访问powerset中的元素。我的问题是:如何做到这一点?

非常感谢您的洞察力。


Tags: 模块对象代码元素chainitertools洞察力powerset
2条回答

下面是一个使用生成器的解决方案:

from itertools import combinations

def all_combos(s):
    n = len(s)
    for r in range(1, n+1):
        for combo in combinations(s, r):
            yield combo

itertools函数返回iterators,即按需延迟生成结果的对象。

可以使用for循环遍历对象,也可以通过调用list()将结果转换为列表:

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))

for result in powerset([1, 2, 3]):
    print(result)

results = list(powerset([1, 2, 3]))
print(results)

还可以将对象存储在变量中,并使用^{} function逐个从迭代器中获取结果。

相关问题 更多 >