[Newby question] List comprehension

Skip Montanaro skip at pobox.com
Fri Aug 6 17:57:39 CEST 2004


    Eelco> # song filter: will return true if the file seems to be an mp3 file. 
    Eelco> # (may not be the best way to do this)
    Eelco> def song(f):
    Eelco>     (name, ext) = os.path.splitext(f)
    Eelco>     return ext.lower() == '.mp3'

    Eelco> # list comprehension walking through a directory tree
    Eelco> [(root, filter(song, files)) for (root, dir, files) in os.walk(os.path.abspath('.')) if filter(song, files)]

In this particular case, since song() only returns True or False, you could
use

    [(root, True) for (root, dir, files) in os.walk(os.path.abspath('.'))
                      if filter(song, files)]

Skip



More information about the Python-list mailing list