filter in for loop

Matthew Woodcraft matthew at woodcraft.me.uk
Thu Aug 28 15:48:30 EDT 2008


GHZ <geraint.williams at gmail.com> writes:

> I would like to say something like:
>
> for filename in os.listdir(DIR) if filename[-4:] == '.xml':
>     <do something>
>
>
> instead of having to say:
>
> for filename in os.listdir(DIR):
>     if filename[-4:] == '.xml':
>         <do something>

If the reason you don't like this one is the extra indentation, one
possibility is

for filename in os.listdir(DIR):
    if filename[-4:] != '.xml':
        continue
    <do something>

-M-



More information about the Python-list mailing list