问题描述
我正在尝试在 Python 3 中创建一个 powerset.我找到了对 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 中的 Powersets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!