how do I generate a cartesian product of several variables using python iterators?
Dear all, Given a variable that takes on, say, three values, I'm trying to generate all possible combinations of, say, triplets of these variables.
While this code does the trick,
site_range=[0,1,2]
states = [(s0,s1,s2) for s0 in site_range for s1 in site_range for s2 in site_range]
it's somewhat, uhm, clumsy, and is only getting worse if I try to do the same for combinations of more than three variables
Hence, my Python 101 questions:
How do I go开发者_如何学Python about rewriting the code above using iterators? I mean, is it possible to have an iterator which would yield the elements of the "states" above?
Is it possible to extend this for generating not only triplets, but also 4-plets, 5-plets and so on?
import itertools
site_range=[0,1,2]
[x for x in itertools.product(site_range, repeat=len(site_range))]
Use itertools.product
:
>>> site_range=[0,1]
>>> list(product(site_range, repeat=3))
[000 001 010 011 100 101 110 111]
Edit As @Glenn Maynard points out in a comment, this is not the cartesian product. For this, you will have to check his answer.
精彩评论