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 :
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!
I interpret non-positive numbers to include 0 so the conditions end up being
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 ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With