[Python-ideas] Accessing the result of comprehension's expression from the conditional
Ben Finney
ben+python at benfinney.id.au
Sun Jun 21 01:35:57 CEST 2009
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]
> > Compare your suggestion:
> >
> > [3*x**2-5*x+4 as y for x in seq if (x % 3 != 2) and (-x < y < x)]
>
> For me, this one is much clearer, understandable, and readable than
> y[0] and y[1]; and you still have the option to split them if you
> think y[0] and y[1] is better.
I hope you'll agree that my above suggestion retains this, without
needing any new syntax.
--
\ “If you go to a costume party at your boss's house, wouldn't |
`\ you think a good costume would be to dress up like the boss's |
_o__) wife? Trust me, it's not.” —Jack Handey |
Ben Finney
More information about the Python-ideas
mailing list