Remove items from a list
Jeff Shannon
jeff at ccvcorp.com
Wed Sep 8 14:27:36 EDT 2004
Paul McGuire wrote:
>"Stan Cook" <scook at elp.rr.com> wrote in message
>news:yWv%c.33126$Dl4.19812 at fe2.texas.rr.com...
>
>
>>Yes, I used the listdir. The list is a list of files in the
>>directory. I want to filter everything out but the ".dbf"
>>files.
>>
>>
>>
>
>You said the answer yourself - "I want to _filter_ everything out but the
>".dbf" files."
>
>Use filter built-in, and use str's endswith() method in place of [-4:] list
>slicing.
>
>dirlist = [ "a.txt", "b.txt", "c.dbf", "d.txt", "e.dbf" ]
>isdbf = lambda x : x.endswith(".dbf")
>print filter( isdbf, dirlist )
>
>gives:
>
>['c.dbf', 'e.dbf']
>
>
Or, one could use a list comprehension and avoid the lambda:
isdbf = [ item for item in dirlist if item.endswith('.dbf') ]
Or better yet ;) one could trade listdir()/filtering for a single call
to glob:
import glob
isdbf = glob.glob('*.dbf')
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list