473,769 Members | 5,727 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

loops -> list/generator comprehensions

I wrote this little piece of code to get a list of relative paths of
all files in or below the current directory (*NIX):

walkList = [(x[0], x[2]) for x in os.walk(".")]
filenames = []
for dir, files in walkList:
filenames.exten d(["/".join([dir, f]) for f in files])

It works fine, I don't need to change it, but I know there is a one
liner list/generator comprehension to do this - I'm just not well
enough versed in comprehensions to figure it out. Can someone please
show me what it is?

Even better, is there a generalized way to transform simple loops into
comprehensions that someone can point me to?

james

Jul 18 '05 #1
10 1406
ja************* ***@gmail.com wrote:
I wrote this little piece of code to get a list of relative paths of
all files in or below the current directory (*NIX):

walkList = [(x[0], x[2]) for x in os.walk(".")]
filenames = []
for dir, files in walkList:
filenames.exten d(["/".join([dir, f]) for f in files])

It works fine, I don't need to change it, but I know there is a one
liner list/generator comprehension to do this - I'm just not well
enough versed in comprehensions to figure it out. Can someone please
show me what it is?
I've used os.path.join instead of "/".join since it's more general, but
other than that, this should be eqivalent:

filenames = [os.path.join(di rpath, filename)
for dirpath, _, filenames in os.walk('.')
for filename in filenames]

Even better, is there a generalized way to transform simple loops into
comprehensions that someone can point me to?


Well, generally, you need to write your loops to use an append, and then
the translation to LC is simpler.

filenames = []
for dirpath, _, filenames in os.walk('.'):
for filename in filenames:
filenames.appen d(os.path.join( dirpath, filename))

Now that you know what it looks like with an append, you simply move the
expression in the append to the top, and leave the fors in the same order:

filenames = [os.path.join(di rpath, filename)
for dirpath, _, filenames in os.walk('.')
for filename in filenames]

HTH,

STeVe
Jul 18 '05 #2
I would be interested to see an example of code that is more concise but
yet as *clear* as the one you already have. I can actually read and
understand what you've got there. That's cool :)
On 6 Feb 2005 11:28:37 -0800, <ja************ ****@gmail.com> wrote:
I wrote this little piece of code to get a list of relative paths of
all files in or below the current directory (*NIX):

walkList = [(x[0], x[2]) for x in os.walk(".")]
filenames = []
for dir, files in walkList:
filenames.exten d(["/".join([dir, f]) for f in files])

It works fine, I don't need to change it, but I know there is a one
liner list/generator comprehension to do this - I'm just not well
enough versed in comprehensions to figure it out. Can someone please
show me what it is?

Even better, is there a generalized way to transform simple loops into
comprehensions that someone can point me to?

james


Jul 18 '05 #3
> HTH,

It does. Thanks.

Jul 18 '05 #4
On 6 Feb 2005 11:28:37 -0800, <ja************ ****@gmail.com> wrote:

walkList = [(x[0], x[2]) for x in os.walk(".")]
filenames = []
for dir, files in walkList:
filenames.exten d(["/".join([dir, f]) for f in files])
Caleb Hattingh top-posted: I would be interested to see an example of code that is more concise
but yet as *clear* as the one you already have.


Out of curiosity, do you find:

filenames = [os.path.join(di rpath, filename)
for dirpath, _, filenames in os.walk('.')
for filename in filenames]

harder to read?

Steve
Jul 18 '05 #5
Sure Steve

Lemme see ... (indentation changed so comments associate with correct bits)
Out of curiosity, do you find:

filenames = [os.path.join(di rpath, filename)

# This is cool
for dirpath, _, filenames in os.walk('.')
# This is getting tricky, whats the '_' for? Which thing
goes where again in a comprehension?
for filename in filenames]
# The hierarchy has nailed me by this point. I
will have to start over...

Yes, yes I do find it more difficult to read. Maybe I just don't know
python as well as I should (certainly not as well as others here!). I
guess it is just familiarity. A single comprehension is ok, nesting them
gets tricky, and 3 times is a strike for me. I will practise :)

keep well
Caleb

Jul 18 '05 #6
Caleb Hattingh wrote:
filenames = [os.path.join(di rpath, filename) # This is cool
for dirpath, _, filenames in os.walk('.')
# This is getting tricky, whats the '_' for?


Nothing to do with the list comprehension really. '_' is a commonly
used variable name for an object that we don't care about. If you look
at the OP's original code, the line:

[(x[0], x[2]) for x in os.walk(".")]

is the equivalent of:

[dirpath, filenames for dirpath, dirnames, filenames in os.walk('.')]

I prefer to give names to the values produced by os.walk -- I think it
makes the usage much clearer. However, since I don't use 'dirnames', I
use '_' to indicate this:

[dirpath, filenames for dirpath, _, filenames in os.walk('.')]

Would

filenames = [os.path.join(di rpath, filename)
for dirpath, dirnames, filenames in os.walk('.')
for filename in filenames]

have been clearer for you? Then all you have to do is remember the
order of the for-loop execution:
# Which thing goes where again in a comprehension?
for filename in filenames]


As mentioned in my other post, the order is identical to that of
for-loops, e.g.

result = []
for dirpath, _, filenames in os.walk('.'):
for filename in filenames:
result.append(o s.path.join(dir path, filename))

is basically equivalent to:

[os.path.join(di rpath, filename)
for dirpath, _, filenames in os.walk('.')
for filename in filenames]

Does that help?

Steve
Jul 18 '05 #7
Steven Bethard <st************ @gmail.com> wrote:
at the OP's original code, the line:

[(x[0], x[2]) for x in os.walk(".")]

is the equivalent of:

[dirpath, filenames for dirpath, dirnames, filenames in os.walk('.')]
Just a nit: you need parentheses in your second LC too, i.e.:

[(dirpath, filenames) for dirpath, dirnames, filenames in os.walk('.')]
I prefer to give names to the values produced by os.walk -- I think it
makes the usage much clearer.


Full agreement here -- those numeric indices are nasty.
Alex
Jul 18 '05 #8
Alex Martelli wrote:
Steven Bethard <st************ @gmail.com> wrote:

at the OP's original code, the line:

[(x[0], x[2]) for x in os.walk(".")]

is the equivalent of:

[dirpath, filenames for dirpath, dirnames, filenames in os.walk('.')]

Just a nit: you need parentheses in your second LC too, i.e.:

[(dirpath, filenames) for dirpath, dirnames, filenames in os.walk('.')]


Yup, you're right (of course) ;) Thanks for the catch!

Steve
Jul 18 '05 #9
Wow, Steve, thanks, you went to some effort here.
I prefer to give names to the values produced by os.walk -- I think it
makes the usage much clearer. However, since I don't use 'dirnames', I
use '_' to indicate this:
Actually, I feel silly for not recognising this - I read about the Python3
suggestion for adding a "with" syntax, and the suggestion was rather to
use something like

_ = instname
_.a = 1
_.b = 2

So I actually have seen this "_" placeholder before :) Sorry bout that.
Would

filenames = [os.path.join(di rpath, filename)
for dirpath, dirnames, filenames in os.walk('.')
for filename in filenames]

have been clearer for you? Then all you have to do is remember the
order of the for-loop execution:


Bizarre as this may sound, it was the '_' that was throwing me off the
whole thing (at the 'grok' level I generally read the newsgroup,
anyway). For some weird reason, I can read *this* comprehension pretty
easily! Does that make sense at all? I figure a little bit of
uncertainty along the way probably derails understanding of the whole
thing a little bit - and (mental note) I *must* remember this when I
explain stuff to people at work, having now experienced it first hand.

Thanks again
Caleb

Jul 18 '05 #10

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

Similar topics

15
6579
by: JustSomeGuy | last post by:
I have a need to make an applicaiton that uses a variable number of nested for loops. for now I'm using a fixed number: for (z=0; z < Z; ++z) for (y=0; y < Y; ++y) for (x=0; x < X; ++x)
4
2136
by: Dr. David Kirkby | last post by:
I have a program that loops through and changes all the elements on an array n times, so my code looks like this: for (n=1; n < n_max; ++n) for(i=imax; i >= 0; --i) { for(j=0 ; j < jmax; ++j) { /* main bulk of code goes here */ } }
46
9936
by: Neptune | last post by:
Hello. I am working my way through Zhang's "Teach yourself C in 24 hrs (2e)" (Sam's series), and for nested loops, he writes (p116) "It's often necessary to create a loop even when you are already in a loop." Then he goes on to portray a contrived example that doesn't tell me under what conditions a nested loop might be favoured as a solution? i.e. what are nested loops useful for? What kinds of algorithms are served by nested loops?...
6
1712
by: Scott Brady Drummonds | last post by:
Hi, everyone, I was in a code review a couple of days ago and noticed one of my coworkers never used for() loops. Instead, he would use while() loops such as the following: i = 0; while (i < n) { ...
77
5247
by: Peter Olcott | last post by:
http://www.tommti-systems.de/go.html?http://www.tommti-systems.de/main-Dateien/reviews/languages/benchmarks.html The above link shows that C# is 450% slower on something as simple as a nested loop. Is this because .NET is inherently slower or does the C# compiler merely produce code that is not as well optimized as the C++ compiler?
17
3056
by: John Salerno | last post by:
I'm reading Text Processing in Python right now and I came across a comment that is helping me to see for loops in a new light. I think because I'm used to the C-style for loop where you create a counter within the loop declaration, for loops have always seemed to me to be about doing something a certain number of times, and not about iterating over an object. The reason for this distinction comes from the fact that I read a lot how...
10
3976
by: Putty | last post by:
In C and C++ and Java, the 'for' statement is a shortcut to make very concise loops. In python, 'for' iterates over elements in a sequence. Is there a way to do this in python that's more concise than 'while'? C: for(i=0; i<length; i++) python: while i < length:
2
2300
by: bitong | last post by:
I'm a little bit confuse with regard to our subject in C..We are now with the Loops..and I was just wondering if given a problem, can you use Do-while loops instead of a for loops or vise versa? are there instances that you must use a Do-while loops instead of a for loops or a while loop? or you can use any types of loops in any given problem?
3
2422
by: monomaniac21 | last post by:
hi all i have a script that retrieves rows from a single table, rows are related to eachother and are retrieved by doing a series of while loops within while loops. bcos each row contains a text field they are fairly large. the net result is that when 60 or so results are reitreved the page size is 400kb! which takes too long to load. is there a way of shorterning this? freeing up the memory say, bcos what is actually displayed is not...
8
7264
by: Nathan Sokalski | last post by:
I have several nested For loops, as follows: For a As Integer = 0 To 255 For b As Integer = 0 To 255 For c As Integer = 0 To 255 If <Boolean ExpressionThen <My CodeElse Exit For Next If Not <Boolean ExpressionThen Exit For Next If Not <Boolean ExpressionThen Exit For
0
9583
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
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,...
1
9990
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,...
1
7406
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5297
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...
0
5445
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3955
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
2
3560
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2814
bsmnconsultancy
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...

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.