Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Add boolean condition to generator

I am generating tuples using :

Z = 1
W = 5
[(x,y) for x in range(Z-2,Z+2)for y in range(W-2,W+2)]

I would like to incorporate some boolean conditions to this generator such as :

  1. Don't include tuples where x equals y.
  2. Don't include tuples where x is non positive.

Is there a dedicated syntax for this task? Something like :

[(x,y) for x in range(Z-2,Z+2)for y in range(W-2,W+2) where (x!=y) and (x>0)]

Thanks!

like image 801
Ohad Dan Avatar asked May 19 '13 07:05

Ohad Dan


1 Answers

I interpret non-positive numbers to include 0 so the conditions end up being

  1. x != y
  2. x >= 0

So the comprehension becomes:

>>> [(x,y) for x in range(Z-2,Z+2) for y in range(W-2,W+2) if x != y and x >= 0]
[(0, 3), (0, 4), (0, 5), (0, 6), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6)]

Another example: Select the numbers between 0 and 99 (inclusive) whose remainder of division for both 2 and 3 equals 0.

>>> [ i for i in range(100) if (i%2==0) and (i%3==0)]
[0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96]

Generally you could describe the syntax as

[ result for variables in iterable if condition ]
like image 115
HennyH Avatar answered Nov 04 '22 20:11

HennyH