[Newby question] List comprehension
sbabbitt at commspeed.net
Fri Aug 6 15:43:39 CEST 2004
"Eelco Hoekema" <eelco.usenet at xs4all.nl> wrote in message
news:pan.2004.08.06.13.22.50.75041 at xs4all.nl...
> I'm trying to get a list of tuples, with each tuple consisting of a
> directory, and a list of files. I only want a tuple if and only if the
> filtered list of files is not empty. And, i want the list of files in the
> tuples to be filtered. For this, i came up with the following code:
> # song filter: will return true if the file seems to be an mp3 file.
> # (may not be the best way to do this)
> def song(f):
> (name, ext) = os.path.splitext(f)
> return ext.lower() == '.mp3'
> # list comprehension walking through a directory tree
> [(root, filter(song, files)) for (root, dir, files) in
os.walk(os.path.abspath('.')) if filter(song, files)]
> Now, this will work. However, it seems kind of silly to call the filter
> twice. Is there a way to keep this in one list comprehension, but with
> just filtering once?
fltres = filter(song, files)
[(root, fltres ) for (root, dir, files) in os.walk(os.path.abspath('.')) if
More information about the Python-list