an ingrate newbie complains

Peter Otten __peter__ at web.de
Wed Feb 4 18:40:07 EST 2004


Dang Griffith wrote:

> 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.

Checking...

Python 2.3.3 (#1, Jan  3 2004, 13:57:08)
[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



More information about the Python-list mailing list