filter in for loop

Jerry Hill malaclypse2 at gmail.com
Thu Aug 28 11:12:47 EDT 2008


On Thu, Aug 28, 2008 at 6:20 AM, GHZ <geraint.williams at gmail.com> wrote:
> is there a shortcut I'm missing?

Well, there's another way to do it, using the filter built in function:

for filename in filter(lambda f:f.endswith('.xml'), os.listdir('.')):
	print filename

You can do the same thing with itertools.ifilter if you need to deal
with arbitrary iterables.  I think your first example of:

for filename in os.listdir('.'):
   if filename.endswith('.xml'):
       <do something>

Is the most readable though.

-- 
Jerry



More information about the Python-list mailing list