[Newby question] List comprehension

Larry Bates lbates at swamisoft.com
Fri Aug 6 15:44:55 CEST 2004


Actually I think (??) this is better done in a loop:
(not tested)

toc=[]
for root, dir, files in os.walk(os.path.abspath('.')):
    mp3files=[f for f in files if f.lower().endswith('.mp3')]
    if mp3files: toc.append((root, mp3files))


HTH,
Larry Bates
Syscon, Inc.

"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:
>
> <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)]
>
>
> </code>
>
> 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?
>
> eelco
>
>





More information about the Python-list mailing list