Using functional tools
David Eppstein
eppstein at ics.uci.edu
Sat May 4 12:51:09 EDT 2002
In article <3CD39DAD.D5BC3F9C at vip.fi>, Pekka Niiranen <krissepu at vip.fi>
wrote:
> I would like to feed every second (or 3rd or 4th .etc) item in a list to
> a function.
>
> list = ['a', 'b', 'c', 'd', 'e']
>
> **some fancy map/filter -trick here**
>
> => list = ['a', function('b'), 'c', function('d'), 'e']
>
> Is there a (functional) way without using for or while -structures ?
This isn't a functional style, but simple generators allow you to avoid
all the index manipulation I've seen in previously-posted solutions:
from __future__ import generators
def alternate(L,F):
L = iter(L)
while 1:
yield L.next()
yield F(L.next())
list = alternate(list,function)
...of course, the result will be an iterator, not a list -- if you
really want a list, call list(alternate(...)) after being careful not to
shadow the built-in "list" function...
--
David Eppstein UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/
More information about the Python-list
mailing list