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.splitex t(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 7 1400
"Eelco Hoekema" <ee**********@x s4all.nl> wrote in message
news:pa******** *************** ****@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.splitex t(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
How about,
fltres = filter(song, files)
[(root, fltres ) for (root, dir, files) in os.walk(os.path .abspath('.')) if
fltres]
Tom
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().endsw ith('.mp3')]
if mp3files: toc.append((roo t, mp3files))
HTH,
Larry Bates
Syscon, Inc.
"Eelco Hoekema" <ee**********@x s4all.nl> wrote in message
news:pa******** *************** ****@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.splitex t(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
Larry Bates schreef: 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().endsw ith('.mp3')] if mp3files: toc.append((roo t, mp3files))
That is about the same as Facundo Bastida said. But then, i like this
better:
tmp = [(root, files) for (root, dir, files) in os.walk(os.path .abspath('.')) if files]
toc = [(root, files) for (root, files) tmp if filter(song, files)]
But that means 2 list comprehensions. Ans i'm just wondering if it can be
done in one, without filtering twice.
eelco
On Fri, 6 Aug 2004, Eelco Hoekema wrote: [(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?
You may do best to split this into two LCs:
temp = [(root, filter(song,fil es)) for (root, dir, files) in
os.walk(os.path .abspath('.'))]
temp = [(root, songs) for (root, songs) in temp if songs]
Or if you prefer, replace the latter with:
temp = filter(temp, lambda x: x[1])
Or even, in 2.4:
temp = filter(temp, itemgetter(1))
In 2.4, you will also be able to replace the first LC with a generator
expression, saving a bit of both memory and processor time (the change
would consist of replacing the brackets with parentheses).
Hope this helps.
Eelco Hoekema schreef: That is about the same as Facundo Bastida said. But then, i like this better:
tmp = [(root, files) for (root, dir, files) in os.walk(os.path .abspath('.')) if files] toc = [(root, files) for (root, files) tmp if filter(song, files)]
Hmm. That doesn't work. It's the other way around, like Christoffer
King showed:
tmp = [(root, files) for (root, dir, files) in os.walk(os.path .abspath('.')) if filter(song, files)]
toc = [(root, files) for (root, files) tmp if files]
eelco
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.splitex t(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
Skip Montanaro schreef: 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,
song() does return True or False, but the return value is used in the
filter, which returns a list.
you could use
[(root, True) for (root, dir, files) in os.walk(os.path .abspath('.')) if filter(song, files)]
That would yield a list of tuples of directories that contain at least one
song. Could still be of use.
eelco This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Fuzzyman |
last post by:
Pythons internal 'pointers' system is certainly causing me a few
headaches..... When I want to copy the contents of a variable I find
it impossible to know whether I've copied the contents *or* just
created a new pointer to the original value....
For example I wanted to initialize a list of empty lists....
a=, , , , ]
I thought there has to be a *really* easy way of doing it - after a
|
by: Mark Elston |
last post by:
I recently stumbled over List Comprehension while reading the
Python Cookbook. I have not kept up with the What's New
sections in the online docs. :)
Anyway, I thought I was following the discussions of List
Comprehension (LC) until I got to Recipe 1.16. In this recipe
we have the following:
arr = , , , ]
print for r in arr] for col in range(len(arr))]
|
by: Moosebumps |
last post by:
Does anyone here find the list comprehension syntax awkward?
I like it because it is an expression rather than a series of statements,
but it is a little harder to maintain it seems.
e.g. you could do:
result =
for element in list:
if element == 'blah':
|
by: Darren Dale |
last post by:
Hi,
I need to replace the following loop with a list comprehension:
res=
for i in arange(10000):
res=res+i
In practice, res is a complex 2D numarray. For this reason, the regular
output of a list comprehension will not work: constructing a list of every
|
by: Xah Lee |
last post by:
is it possible to write python code without any indentation?
Xah
xah@xahlee.org
http://xahlee.org/PageTwo_dir/more.html
| |
by: a |
last post by:
can someone tell me how to use them
thanks
|
by: beginner |
last post by:
Hi All,
How do I map a list to two lists with list comprehension?
For example, if I have x=, ]
What I want is a new list of list that has four sub-lists:
, , , ]
|
by: idiolect |
last post by:
Hi all - Sorry to plague you with another newbie question from a
lurker. Hopefully, this will be simple.
I have a list full of RGB pixel values read from an image. I want to
test each RGB band value per pixel, and set it to something else if it
meets or falls below a certain threshold - i.e., a Red value of 0
would be changed to 50.
I've built my list by using a Python Image Library statement akin to
the following:
|
by: Pat |
last post by:
I have written chunks of Python code that look this:
new_array =
for a in array:
if not len( a ):
continue
new_array.append( a )
and...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |