E
Eelco Hoekema
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
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