Using filter()

Calvelo Daniel dcalvelo at pharion.univ-lille2.fr
Tue Jul 18 13:47:07 EDT 2000


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