Python - Add boolean condition to generator -
i generating tuples using :
z = 1 w = 5 [(x,y) x in range(z-2,z+2)for y in range(w-2,w+2)]
i incorporate boolean conditions generator such :
- don't include tuples x equals y.
- don't include tuples x non positive.
is there dedicated syntax task? :
[(x,y) x in range(z-2,z+2)for y in range(w-2,w+2) (x!=y) , (x>0)]
thanks!
i interpret non-positive include 0 conditions end being
- x != y
- x >= 0
so comprehension becomes:
>>> [(x,y) x in range(z-2,z+2) y in range(w-2,w+2) if x != y , 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 numbers between 0 , 99 (inclusive) remainder of division both 0 , 3 equals 0.
>>> [ in range(100) if (i%2==0) , (i%3==0)] [0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96]
generally describe syntax as
[ result variables in iterable if condition ]
Comments
Post a Comment