[Tutor] map, filter and lambda functions
Roeland Rengelink
r.b.rigilink@chello.nl
Thu, 23 Aug 2001 07:23:50 +0200
Sheila King wrote:
[snip]
>
> Here's the new, shorter version:
>
> checklist = string.split(filetext, "\n")
> checklist = filter(lambda x: x != '', checklist)
> checklist = map(lambda x: string.strip(x), checklist)
> checklist = map(lambda x: string.upper(x), checklist)
>
> The thing is, I can't use list comprehensions in this script, since my
> webhost is only running Python 1.5.2. Given this restriction, is my
> second version the best (most efficient) way of handling such a code
> block? Is there a way to do this without lambda functions, or are they
> pretty much needed in this case?>
Hi Sheila,
Two things,
- map can take any function object as its first argument
- filter may take None as its first argument, in which case it will
return the sequence of items that evaluate to true.
So:
checklist = string.split(filetext, '\n')
checklist = filter(None, checklist)
checklist = map(string.strip, checklist)
checklist = map(string.upper, checklist)
If checklist is rather long, the last two may be written mor efficiently
as:
checklist = map(lambda x:string.upper(string.strip(x)), checklist)
Hope this helps,
Roeland
--
r.b.rigilink@chello.nl
"Half of what I say is nonsense. Unfortunately I don't know which half"