Using filter()
Calvelo Daniel
dcalvelo at pharion.univ-lille2.fr
Wed Jul 19 05:16:00 EDT 2000
Larry Whitley <ldw at us.ibm.com> wrote:
: Thanks, that certainly works.
: I don't understand why lambda needs the second parameter. When I
: experiment with
:
: filter( lambda x: string.find( x, name) == 0, fileList)
:
: in place of
:
: filter( lambda x,sf=string.find: sf(x, name )==0, fileList )
:
: it works as well. I suspect that your codeing come from something more
: general. Can you explain the reason the sf=string.find construction is
: useful in this context?
Doing the sf=string.find trick saves one name lookup. I have, with fileList
being a list of 10000 "abc" and 10000 "bbc":
>>> import time
>>> tic=time.clock(); None=filter( lambda x: string.find( x, "a") == 0, fileList); time.clock()-tic
1.92
>>> tic=time.clock(); None=filter( lambda x,sf=string.find: sf( x, "a") == 0, fileList); time.clock()-tic
1.14
(These are typical timings on my machine with Python1.5.2 and have nothing
but illustrative purposes.)
Besides, it's "safer" in a sense: It works for you because 'string' is a
global or module global. But if you do stg like:
def a():
import string
return filter( lambda x: string.find( x, <name>) == 0, <fileList>)
then 'string' is *not* looked up in a's namespace, whereas it is with the
other trick. I wouldn't recommend such practices anyway but who knows.
You might want to have a look at Skip Montanaro's Pyhton Performance Tips
at http://www.musi-cal.com/~skip/python/fastpython.html
HTIU
Python-42K-will-have-nested-namespaces!-really!-ly y'rs, Daniel
-- Daniel Calvelo Aros
calvelo at lifl.fr
More information about the Python-list
mailing list