I can ask my question best by just giving an example. Let's say I want to use a list comprehension to generate a set of 3-element tuples from two loops, something like this:
[ (y+z,y,z) for y in range(10) if y%2==0 for z in range(20) if z%3==0 ]
This works, giving me
[(0, 0, 0), (3, 0, 3), (6, 0, 6), (9, 0, 9), (12, 0, 12), (15, 0, 15), ... ]
I am wondering, though, if there is a way to do it more cleanly, something to the effect of
[ (x,y,z) for y in range(10) if y%2==0 for z in range(20) if z%3==0 ... somehow defining x(y,z) ... ]
I would consider something like this to be more clean, especially since what I really need to do is much more complicated than the example I give here. Everything I have tried has given me a syntax error.
You can do:
out = [
(x, y, z)
for y in range(10)
if y % 2 == 0
for z in range(20)
if z % 3 == 0
for x in [y + z] # <-- initialize `x` in list-comprehension
]
This is optimized since Python 3.9: https://docs.python.org/3/whatsnew/3.9.html#optimizations
I would skip the division and just generate the desired multiples explicitly.
[(y+z,y,z) for y in range(0, 10, 2) for z in range(0, 20, 3)]
Now you can use itertools.product
instead of two generators.
[(sum(p), *p) for p in product(range(0, 10, 2), range(0, 20, 3))]
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