On 2022-09-01 13:33:16 -0700, James Tsai wrote: > 在 2022年9月1日星期四 UTC+2 18:34:36,<[email protected]> 写道: > > On 9/1/22, James Tsai <[email protected]> wrote: > > > > > > I find it very useful if I am allowed to define new local variables in a > > > list comprehension. For example, I wish to have something like > > > [(x, y) for x in range(10) for y := x ** 2 if x + y < 80], or > > > [(x, y) for x in range(10) with y := x ** 2 if x + y < 80]. > > > > > > For now this functionality can be achieved by writing > > > [(x, y) for x in range(10) for y in [x ** 2] if x + y < 80]. > > You can assign a local variable in the `if` expression. For example: > > > > >>> [(x, y) for x in range(10) if x + (y := x**2) < 30] > > [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)] > > Yeah this works great but like [(x, y) for x in range(10) for y in > [x**2]] I written before, is kind of a hack. And if initially I do not > need an "if" condition in the list comprehension, this becomes less > convenient. I still can write > >>> [(x, y) for x in range(10) if (y := x**2) or True]
In that case
[(x, x**2) for x in range(10)]
seems to be somewhat more readable.
I would also say that
[(x, x**2) for x in range(10) if x + x**2 < 80]
doesn't really seem worse than any of the variants with y in it.
(Yes, I get that your real duplicated expression is probably a bit more
complex than `x**2`, but by the time a temporary variable really
improves readability it's probably a good time to split that across
multiple lines, too.)
hp
--
_ | Peter J. Holzer | Story must make more sense than reality.
|_|_) | |
| | | [email protected] | -- Charles Stross, "Creative writing
__/ | http://www.hjp.at/ | challenge!"
signature.asc
Description: PGP signature
-- https://mail.python.org/mailman/listinfo/python-list
