Peter Otten <(E-Mail Removed)> wrote in message news:<bvrvsn$pdn$02$(E-Mail Removed)-online.com>...

> Dang Griffith wrote:

>

> > On Wed, 04 Feb 2004 19:46:28 +0100, Peter Otten <(E-Mail Removed)>

> > wrote:

> >

> >>> That kind of syntax would be especially welcome in list comprehensions:

> >>>

> >>> [f(x,y) for x in list if y=g(x)<=0]

> >>>

> >>> If g(x) is a fairly complicated expression, and y occurs several times

> >>> in f(x,y), considerable clarity could be gained.

> >>

> >>Is the above list comprehension that frequent? Then how about

> >>

> >>[f(x, y) for x, y in [(x, g(x)) for x in lst] if cond(y)]

> >>

> >>With the arrival of generator expressions, some of the overhead (the

> >>intermediate list) is bound to go away. In the mean time, there's still

> >>that good old for loop, which IMHO is still the most readible solution if

> >>things get really complicated.

> >

> > I couldn't get your example to run.

>

> Checking...

>

> Python 2.3.3 (#1, Jan 3 2004, 13:57:0

> [GCC 3.2] on linux2

> Type "help", "copyright", "credits" or "license" for more information.

> >>> def f(x, y):

> ... return '%d%d' % (x, y)

> ...

> >>> def g(x): return 2*x

> ...

> >>> def cond(x): return x % 10 == 2

> ...

> >>> lst = range(10)

> >>> [f(x, y) for x, y in [(x, g(x)) for x in lst] if cond(y)]

> ['12', '612']

> >>>

>

> Seems to work. Maybe you overlooked the nested list comps?

>

> > If g is a generator expression, this works for me:

> >

> > [f(x, y) for x in lst for y in g(x) if cond(y)]

>

> This is elegant.

>

> Peter
OIC--you mentioned generators and I defined g as yield 2*x.

You're right--yours works with non-generator, mine works with generator.

Maybe this should be a new thread, but... is defining a generator

like I did here, i.e. one that really only returns one value considered

an abuse of generators? It sure seemed convenient for this application.

def g(x): yield 2*x

--dang