[Question] Functional style with lists

Dan Schmidt dfan at harmonixmusic.com
Tue May 4 17:14:13 EDT 1999


David Berthelot <berthelo at lirmm.fr> writes:

| Hi,
| 
| i like to program in functional style, for instance, to get the sum of
| square values for a range i do :
| >>> reduce(lambda x,y:x+y,map(lambda x:x*x,range(10)))
| 285
| >>>
| 
| Ok, but i've a problem, how to access a list element in this fashion,
| for instance:
| >>> L = [ ("John",40), ("Monthy",35)]
| 
| I would like to sum the numeric values by using map.
| I've tried this:
| >>> map(lamda x,y:x+y,map(L.getitem,(1,)*len(L)))
| 
| But of course it doesn't work...

I think you meant 'reduce' instead of 'map' at the beginning, as in
your first example.

Also, of course, 'lamda' should be 'lambda'.

To solve your problem, instead of trying to use __getitem__ somehow,
you can just write another lambda:

>>> L = [ ("John",40), ("Monthy",35)]
>>> reduce (lambda x,y:x+y, map(lambda l:l[1], L))
75

In this case the story has a happy ending.  But be aware that Python's
support for functional programming is not very complete, and often it
is harder to do things functionally than to do them with iteration.

-- 
                 Dan Schmidt -> dfan at harmonixmusic.com, dfan at alum.mit.edu
Honest Bob & the                http://www2.thecia.net/users/dfan/
Factory-to-Dealer Incentives -> http://www2.thecia.net/users/dfan/hbob/
          Gamelan Galak Tika -> http://web.mit.edu/galak-tika/www/




More information about the Python-list mailing list