[Newby question] List comprehension
Batista, Facundo
FBatista at uniFON.com.ar
Fri Aug 6 09:35:52 EDT 2004
[Eelco Hoekema]
#- # 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?
files = []
for (root, dir, files) in os.walk(os.path.abspath('.')):
mp3files = filter(song, files)
if mp3files:
files.append((root, mp3files))
Now, explain me why a list comprehension is better here.
. Facundo
More information about the Python-list
mailing list