473,513 Members | 2,558 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

[Newby question] List comprehension


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
Jul 18 '05 #1
7 1384

"Eelco Hoekema" <ee**********@xs4all.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.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

How about,

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

Tom
Jul 18 '05 #2
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" <ee**********@xs4all.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.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

Jul 18 '05 #3
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().endswith('.mp3')]
if mp3files: toc.append((root, 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

Jul 18 '05 #4
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,files)) 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.

Jul 18 '05 #5
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

Jul 18 '05 #6
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
Jul 18 '05 #7
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

Jul 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
40592
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*...
1
1283
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...
35
2929
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...
15
1602
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...
32
2246
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
18
460
by: a | last post by:
can someone tell me how to use them thanks
12
2269
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: , , , ]
7
1504
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...
5
1080
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...
0
7161
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...
0
7539
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7101
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...
1
5089
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4746
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...
0
3234
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...
0
3222
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1596
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 ...
1
802
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.