Suggestion for impriving list comprehensions

Steven D. Majewski sdm7g at Virginia.EDU
Thu Jul 26 21:20:54 EDT 2001


On 26 Jul 2001, Thomas Bellman wrote:

> or my personal favourite
> 
>     map(lambda x,g=fib(): g.next(), range(N))
> 

Cool. 

I see I can get the odd values from the first 10 fibonacci numbers with:

>>> def odd(x): return x % 2 
... 
>>> def even(x) : return not(odd(x))
... 
>>> filter( odd, map( lambda n,f=fib().next: f(), range(10) ))
[1, 1, 3, 5, 13, 21, 55]


But the first 10 odd fibonacci numbers doesn't work the same way. 

But Re: Guido's suggestion about an iterator algebra : 
 maybe what we need are iterator versions of map, filter, reduce, etc. 


Given:

>>> def gfilter( f, s ):
...     for x in s:
...             if f(x): yield x

Then the first 10 odd fibonacci numbers are:

>>> map( lambda n,f=gfilter( odd, fib() ).next: f(), range(10) )
[1, 1, 3, 5, 13, 21, 55, 89, 233, 377]



( I'm not completely sure that I actually *like* all the iterator 
  syntax and semantics -- the extra indirection which sometimes
  needs to be explicit  ( the "next" attribute ) but sometimes 
  gets done automagically by 'for' is something I'm not quite 
  used to yet! ) 


-- Steve Majewski






More information about the Python-list mailing list