[Tutor] map, filter and lambda functions
Sheila King
sheila@thinkspot.net
Wed, 22 Aug 2001 16:16:13 -0700
I feel so smart, today! I finally figured out a situation where those
map, lambda and filter functions come in handy, and they are making
sense to me, now!
I am running a script on my website, to screen my incoming e-mail. I
have a textfile on the site, that has e-mail addresses in it, and I read
them into a list and compare parts of the message headers against the
list to see if I want the e-mail or not. (That's a simplified
explanation, but the essential idea.)
Anyhow, I think I have really improved the code, by removing some
lookups on the list, and some loops and stuff.
Here is an earlier version of a part of the code:
checklist = string.split(filetext, "\n")
for item in checklist:
if item != '':
itemIdx = checklist.index(item)
item = string.strip(item)
item = string.upper(item)
checklist[itemIdx] = item
else:
checklist.remove(item)
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?
--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/