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 = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]]
print [[r[col] for r in arr] for col in range(len(arr[0]))]
-> [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
For all the previous LC examples (and in the What's New
writeup for 2.0) it was stated (or implied) that code of the form:
[ expression for expr in sequence1
for expr2 in sequence2 ...
for exprN in sequenceN
if condition ]
was equivalent to:
for expr1 in sequence1:
for expr2 in sequence2:
...
for exprN in sequenceN:
if (condition):
# Append the value of
# the expression to the
# resulting list.
I thought I understood this until I got to the above recipe. Here
it looks like the order of evaluation is reversed. That is, instead
of translating to:
for r[col] in arr:
for col in range(len(arr[0])):
...
we actually have
for col in range(len(arr[0])):
for r[col] in arr:
...
And all of this due to a placement of '[ ... ]' around the 'inner'
loop.
The reference documentation doesn't explain this either. The grammar
page on List Displays doesn't seem to give any insight.
While I don't really understand it I may have some kind of rationale.
Please let me know if this is correct.
The print... command is a LC with a single expression and a single 'for'
construct. The expression, itself, is also a LC. When the command is
executed 'col' is set to 0 (the first value in the range) and this is
'passed' to the expression for evaluation. This evaluation results in
a list generated by the 'inner' LC which iterates over each row in the
array and, therefore, generates the list: [1, 4, 7, 10].
The next step is to go back to 'col' and extract the next value (1) and
generate the next list, etc.
Well, hmmmmm. OK. Maybe I do understand it. It just wasn't apparent
at first.
Am I close, or did I guess wrong?
Mark 1 1299
Mark Elston wrote in message ... Anyway, I thought I was following the discussions of List Comprehensio n (LC) until I got to Recipe 1.16. In this recipe we have the following:
arr = [[1,2,3], [4,5,6], [7,8,9], [10,11,12]] print [[r[col] for r in arr] for col in range(len(arr[0]))] -> [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
All the second line is saying, is, for every pass of the innermost (here,
rightmost) for-loop, execute this list comprehension: [r[col] for r in arr].
Same as:
res = []
for col in range(3):
res.append([r[col] for r in arr])
Unrolling a bit more:
res = []
for col in range(3):
innerres = []
for r in arr:
innerres.append (r[col])
res.append(inne rres)
Note this is NOT the same as [r[col] for col in range(3) for r in arr]!
res = []
for col in range(3):
for r in arr:
res.append(r[col])
-> [1, 4, 7, 10, 2, 5, 8, 11, 3, 6, 9, 12]
See? It's flattened, because the list comp's expression evaluates to an
integer instead of a list.
I thought I understood this until I got to the above recipe. Here it looks like the order of evaluation is reversed. That is, instead of translating to:
for r[col] in arr: for col in range(len(arr[0])): ...
we actually have
for col in range(len(arr[0])): for r[col] in arr: ...
Nope. See above.
While I don't really understand it I may have some kind of rationale. Please let me know if this is correct.
You're thinking too much. :)
The expression, itself, is also a LC.
This is the part that's causing you confusion. This is a nested list comp:
for every iteration in the outer list comp, execute the expression. The
fact that the expression happens to be a list comp itself just means that
the outer list comp will append a new list on each pass.
Wrap the inner list comp in a function call and it will make sense to you:
def innercomp(col):
return [r[col] for r in arr]
[innercomp(col) for col in range(3)]
-> [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
(It's also significantly slower.)
Well, hmmmmm. OK. Maybe I do understand it. It just wasn't apparent at first.
Am I close, or did I guess wrong?
You got it.
Note, however, that the same thing is far easier with zip(): zip(*arr)
[(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)]
If you need the items to be lists,
[list(i) for i in zip(*arr)]
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
or,
map(list, zip(*arr))
[[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]]
--
Francis Avila This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Chris P. |
last post by:
Hi. I've made a program that logs onto a telnet server, enters a
command, and then creates a list of useful information out of the
information that is dumped to the screen as a result of the command.
Here's a generic version of the code in question:
#####
# Prior code opens telnet connection "tn" and logs in.
tn.read_until('> ')
tn.write('THE COMMAND IS HERE\n')
|
by: Mahesh Padmanabhan |
last post by:
Hi,
When list comprehension was added to the language, I had a lot of
trouble understanding it but now that I am familiar with it, I am not
sure how I programmed in Python without it.
Now I see that generator expressions have been added to the language
with 2.4 and I question the need for it. I know that it allows for lazy
evaluation which speeds things up for larger lists but why was it
necessary to add it instead of improving list...
|
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: a |
last post by:
can someone tell me how to use them
thanks
|
by: Gregory Guthrie |
last post by:
Sorry for a simple question- but I don't understand how to parse this use of
a list comprehension.
The "or" clauses are odd to me.
It also seems like it is being overly clever (?) in using a lc expression as
a for loop to drive the recursion.
Thanks for any insight!
Gregory
| |
by: bvdp |
last post by:
Please help my poor brain :) Every time I try to do a list
comprehension I find I just don't comprehend ...
Anyway, I have the following bit of code:
seq =
tmp =
for a in range(len(seq)):
tmp.extend(*seq)
|
by: beginner |
last post by:
Hi,
Does anyone know how to put an assertion in list comprehension? I have
the following list comprehension, but I want to use an assertion to
check the contents of rec_stdl. I ended up using another loop which
essentially duplicates the functions of list comprehension. It just
look like a waste of coding and computer time to me.
I just wish I could put the assertions into list comprehensions.
|
by: beginner |
last post by:
Hi All,
If I have a list comprehension:
ab=
c = "ABC"
print c
|
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: mh |
last post by:
I googled and wiki'ed, but couldn't find a concise clear answer
as to how python "list comprehensions" got their name.
Who picked the name? What was the direct inspiration, another
language? What language was the first to have such a construct?
I get that it's based on set notation.
Thanks!
Mark
|
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: 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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
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: 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...
|
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: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
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: 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...
| |