
You could write: [x|y <- l, x <- [f(y)], x > 0] Oh, wait. Thats Haskell. And even in haskell you would write: [x|x <- map f l, x > 0] In Python you can write: [x for x in map(f,l) if x > 0] In Python 2.x you may want to write: from itertools import imap [x for x in imap(f,l) if x > 0] A more SQL like approach that would fit somewhat with pythons syntax would be (as you can see its exactly the same lengths as the above but needs a new name): [f(x) as y for x in l if y > 0] Because in SQL you can write (IIRC): select f(x) as y from l where y > 0; Maybe something like .Nets LINQ would be a nice idea to integrate in python? -panzi Lie Ryan wrote:
In list/generator comprehension, currently we have no way to access the result of the expression and have to write something like this:
[f(x) for x in l if f(x) > 0]
if f() is heavy or non-pure (i.e. have side effects), calling f() twice might be undesirable.
Even if f() is not a function such as
[x + 1 for x in l if x + 1 > 0]
it looks ugly since we're repeating ourself.
We can work around it like this:
[y for y in (f(x) for x in l) if y > 0]
but then we have an unnecessary nested loop comprehension.
I'm suggesting about something like:
[f(x) for x in l if @ > 0]
where @ is the result of the listcomp's expression (i.e. f(x))
Personally, I don't like the use of symbols like @, as python is not perl. I'm still thinking of a better syntax/approach and is open for suggestion.
What do you guys think?