[Tutor] map, filter and lambda functions
Thu, 23 Aug 2001 01:01:58 +0100
On 22 Aug 2001, at 16:16, Sheila King wrote:
> 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
My opinion is, the best version is the one which makes you smile
more. :) Out of the two, I like the second one more.
> Is there a way to do this without lambda functions, or are they
> pretty much needed in this case?
You don't need to put lambda functions, you can just provide
string.strip and string.upper without using lambda what-so-ever.
I would personally, however, write this:
checklist = map (lambda x: x.strip().upper(), checklist)
or, if Python 1.5.2 doesn't like that:
checklist = map (lambda x: string.upper(string.strip(x)), checklist)
Which reduces it down to one line. But you might not want that.
You could also replace the lambda function that's used in filter with
"None". IIRC, that will only return objects which have a positive
truth value (in the case of strings, this would only be non-empty
If you were really daring, you could put all that into one large
checklist = map (string.upper, map (string.strip, filter (None,
That *might* work, I can't be bothered to test it. :)
Use whatever version you are happiest with. I'd go with whatever
version is easier to understand when you read it, which, out of the
two you've given us, would be the second one.