[Python-ideas] Accessing the result of comprehension's expression from the conditional
Lie Ryan
lie.1296 at gmail.com
Sun Jun 21 08:36:27 CEST 2009
Ben Finney wrote:
> Lie Ryan <lie.1296 at gmail.com> writes:
>
>> Steven D'Aprano wrote:
>> <snip>
>>> The only case it doesn't cover is where the second filter depends on
>>> the value of x, and even that can be covered with a *tiny* bit more
>>> work:
>>>
>>> gen = ((x, 3*x**2-5*x+4) for x in seq if x % 3 != 2)
>>> result = [y[1] for y in gen if -y[0] < y[1] < y[0]]
>>>
>>> It requires no new syntax, no changes to the behaviour of list
>>> comps, no new meaning on "as", it's understandable and readable.
>
> I think it would be more readable without index references, but instead
> using tuple unpacking::
>
> gen = ((x, 3*x**2-5*x+4) for x in seq if x % 3 != 2)
> result = [b for (a, b) in gen if -a < b < a]
>
> It can even be done as a single expression without (IMO) significantly
> affecting readability::
>
> result = [
> b for (a, b) in
> ((x, 3*x**2-5*x+4) for x in seq if x % 3 != 2)
> if -a < b < a]
IMHO, when a comprehension requires more than a single line, it should
turn into explicit loop.
<snip>
More information about the Python-ideas
mailing list