Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

Powersets in Python using itertools

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?

Many thanks in advance for your insights.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

itertools functions return iterators, objects that produce results lazily, on demand.

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)

You can also store the object in a variable and use the next() function to get results from the iterator one by one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...