Using functional tools
Ken Seehof
kseehof at neuralintegrator.com
Sat May 4 06:47:50 EDT 2002
> Pekka Niiranen says:
> > 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 ?
I said:
> Okay, if you find obfuscation by functional programming
> as entertaining as I do, try this pattern:
>
> >>> def f(x):
> ... return x*10
> ...
> >>> n = 3
> >>> a = [1,2,3,4,5,6,7,8,9]
> >>> [((i+1)%n) and a[i] or f(a[i]) for i in range(len(a))]
> [1, 2, 30, 4, 5, 60, 7, 8, 90]
I forgot to mention that this won't work if the list contains
values that evaluate to false. However, since you were in
the context of reading lines, I figured there's no problem
(note that an empty line is '\n', which is a nonzero value)
- Ken
More information about the Python-list
mailing list