[Tutor] Tweaking list comprehensions
Tony Meyer
tameyer at ihug.co.nz
Mon Feb 14 03:22:38 CET 2005
>> def approachB(files):
>>
>> isHTML = [filename if filename.endswith('.htm') or\
>> filename.endswith(.html') for filename in files]
>> return isHTML
>
> No, it should be...
>
> isHTML = [filename for filename in files if
> filename.endswith('.htm') or\
> filename.endswith('.html') for filename in files]
Actually:
isHTML = [filename for filename in files if filename.endswith('.htm') or \
filename.endswith('.html')]
>>> files = "a.html", "b.htm", "c.txt"
>>> [filename for filename in files if filename.endswith('.htm') or
filename.endswith('.html') for filename in files]
['a.html', 'b.htm', 'c.txt', 'a.html', 'b.htm', 'c.txt']
>>> [filename for filename in files if filename.endswith('.htm') or
filename.endswith('.html')]
['a.html', 'b.htm']
FWIW, if you're getting "files" from a directory listing of a local drive,
you might be able to use 'glob.glob("*.htm?")' instead.
=Tony.Meyer
More information about the Tutor
mailing list