filter in for loop

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Thu Aug 28 12:28:26 CEST 2008


GHZ a écrit :
> I would like to say something like:
> 
> for x in l if <expression>:
>     <do something>
> 
> e.g.
> 
> 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>
> 
> or
> 
> for filename in (f for f in os.listdir(DIR) if f[-4] == '.xml'):
>     <do something>
> 
> 
> is there a shortcut I'm missing?

Not AFAIK, and I sometimes regret it - but the first alternative is good 
enough IMHO.

<ot>
I'd rather use os.path.splitext or str.endswith than subscript, but YMMV.
</ot>



More information about the Python-list mailing list