Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: single-line cartesian product for-loop

Did you know you can do this?

>>> [(x,y) for x in xrange(2) for y in xrange(5)]
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 1), (1, 2), (1, 3), (1, 4)]

It's neat. Is there a for loop version or can one only do this for list comprehensions?

EDIT: I think my question was misunderstood. I want to know if there is special syntax for this:

for x in xrange(2) <AND> y in xrange(5):
    print "do stuff here"
    print "which doesn't fit into a list comprehension"
    print "like printing x and y cause print is a statement", x, y

I could do this, but it seems a bit repetitive:

for x,y in ((x,y) for x in xrange(2) for y in xrange(5)):
    print x, y
like image 358
Claudiu Avatar asked Dec 10 '22 09:12

Claudiu


1 Answers

Well there's no syntax for what you want, but there is itertools.product.

>>> import itertools
>>> for x, y in itertools.product([1,2,3,4], [5,6,7,8]): print x, y
... 
1 5
1 6
1 7
1 8
[ ... and so on ... ]
like image 131
senderle Avatar answered Dec 18 '22 11:12

senderle