[Tutor] Extracting filenames from a List?

Tom Jenkins tjenkins@devis.com
21 Jan 2002 15:07:17 -0500


Hello,

On Mon, 2002-01-21 at 14:34, Troels Petersen wrote:
> Hi,
> 
> I have a list containing filenames.
> 
> What I would like to do is to extract all files ending in '.jpg' - the case
> does not matter. Everything ending in '.JpG' should be extracted.
> 
> What is the best way to do this? A Regular expression or..? It should fast
> and something that can be understood by a newbie like me (I need to finish
> the 2 last chapters of 'How to Think Like A Computer Scientist').

well, how fast is fast? <grin>
lets take a quicky algorithm and see if it is fast enough for your
purpose.  (that's what we're looking for btw "fast enough")

you have a list of filenames, you want to iterate over the list.  for
each filename look at the last 4 characters and see if they match
'.jpg'.  what you don't say is how you want these matching files
returned... i'll assume a list.

def findJPGs(filenameList):
   results = []
   for x in filenameList:  
      #this gives use the iteration over the list
      if x[-4:].lower() == '.jpg':
         # this checks the last 4 characters
         results.append(x)
   return results

how fast is this?
well on my system a list of 1700 filenames takes milliseconds.  is that
fast enough?

if not then you can use list comprehension to see if the code is
faster...

def findJPGs2(filenameList):
   return [x for x in filenameList if x[-4:].lower() == '.jpg']

if you look closely, you see that all the code from findJPG is now in
the list comprehension.  Does this run faster?  just barely on my
system.

do you want to get faster?  well, then go ahead and look at the
algorithm.  see if anything in there can be done better/faster.  for me,
this is "fast enough"


-- 

Tom Jenkins
Development InfoStructure
http://www.devis.com