an ingrate newbie complains

Dang Griffith noemail at noemail4u.com
Wed Feb 4 14:22:30 EST 2004


On Wed, 04 Feb 2004 19:46:28 +0100, Peter Otten <__peter__ at web.de>
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.

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)]

Elaine?  Readable enough?

    --dang
p.s.
>>> def f(x, y):
...     return '%d%d' % (x, y)
...
>>> def g(x):
...     yield 2 * x
...
>>> def cond(y):
...     return y % 10 == 2
...
>>> lst = range(10)
>>> print [f(x, y) for x in lst for y in g(x) if cond(y)]
['12', '612']




More information about the Python-list mailing list