问题描述
我正在尝试在Python 3中创建电源集.我找到了对itertools
的引用 模块,并且我使用了该页面上提供的powerset代码.问题:代码返回对itertools.chain
对象的引用,而我想访问Powerset中的元素.我的问题:如何实现?
I'm trying to create a powerset in Python 3. I found a reference to the itertools
module, and I've used the powerset code provided on that page. The problem: the code returns a reference to an itertools.chain
object, whereas I want access to the elements in the powerset. My question: how to accomplish this?
在此先感谢您的见解.
推荐答案
itertools
函数返回 迭代器 ,即按需延迟生成结果的对象.
itertools
functions return iterators, objects that produce results lazily, on demand.
您可以使用for
循环遍历对象,也可以通过在其上调用list()
将结果转换为列表:
You could either loop over the object with a for
loop, or turn the result into a list by calling list()
on it:
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)
您还可以将对象存储在变量中,并使用 next()
函数逐一从迭代器获取结果.
You can also store the object in a variable and use the next()
function to get results from the iterator one by one.
这篇关于使用itertools的Python中的Powerset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!