Using filter()

Larry Whitley ldw at us.ibm.com
Tue Jul 18 16:53:54 EDT 2000


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?

Thanks,
Larry

"Calvelo Daniel" <dcalvelo at pharion.univ-lille2.fr> wrote in message
news:8l256r$d7n$1 at netserv.univ-lille1.fr...
> Larry Whitley <ldw at us.ibm.com> wrote:
> : I have a simple problem and from the description, filter() seems like a
> : match.  But I can't figure out how to make it work.  Here's the code
without
> : using filter()
>
> : include string, os
>
> : def filter1( fileList, name ):
> : #--------------------------------------------------------
> : # matches name to the first characters of a file in the file list
> :  temp = []
> :  for i in range(len(fileList)):
> :     if string.find( fileList[i], name ) == 0:
> :         temp.append( fileList[i] )
> :  return temp
>
> This:
>
> filter( lambda x,sf=string.find: sf(x, name )==0, fileList )
>
> gives you back the same result. In this and filter2(), the point
> of using the built-in filter is to move out of the loop and design
> the test function element-wise. filter then does the job.
>
> : def filter2( filelist, aString ):
> : #-------------------------------------------------
> : # finds aString somewhere in the file list
> :  temp = []
> :  for i in range(len(filelist)):
> :     if string.find( filelist[i], aString ) != -1: # is in the string
> : somewhere
> :         temp.append( filelist[i] )
> :  return temp
>
> Likewise:
>
> filter( lambda x,sf=string.find: sf(x, name ) !=-1, fileList )
>
> [snip main]
>
> : I suspect using filter() would simplify this.  Can someone help?
>
> : Larry
>
> HTH
>
> docstrings-are-your-friend-if-not-then-they-are-enemies-to-be-feared-ly
y'rs
>
> Daniel.
>
> -- Daniel Calvelo Aros
>      calvelo at lifl.fr





More information about the Python-list mailing list