Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
6b86fc96
Commit
6b86fc96
authored
Dec 14, 2007
by
Georg Brandl
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Add a section about nested listcomps to the tutorial.
Thanks to Ian Bruntlett and Robert Lehmann.
parent
7e13a02f
Changes
2
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
43 additions
and
0 deletions
+43
-0
Doc/ACKS.txt
Doc/ACKS.txt
+1
-0
Doc/tutorial/datastructures.rst
Doc/tutorial/datastructures.rst
+42
-0
No files found.
Doc/ACKS.txt
View file @
6b86fc96
...
...
@@ -28,6 +28,7 @@ docs@python.org), and we'll be glad to correct the problem.
* Aaron Brancotti
* Georg Brandl
* Keith Briggs
* Ian Bruntlett
* Lee Busby
* Lorenzo M. Catucci
* Carl Cerecke
...
...
Doc/tutorial/datastructures.rst
View file @
6b86fc96
...
...
@@ -265,6 +265,48 @@ to complex expressions and nested functions::
['3.1', '3.14', '3.142', '3.1416', '3.14159']
Nested List Comprehensions
--------------------------
If you've got the stomach for it, list comprehensions can be nested. They are a
powerful tool but -- like all powerful tools -- they need to be used carefully,
if at all.
Consider the following example of a 3x3 matrix held as a list containing three
lists, one list per row::
>>> mat = [
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9],
... ]
Now, if you wanted to swap rows and columns, you could use a list
comprehension::
>>> print [[row[i] for row in mat] for i in [0, 1, 2]]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Special care has to be taken for the *nested* list comprehension:
To avoid apprehension when nesting list comprehensions, read from right to
left.
A more verbose version of this snippet shows the flow explicitly::
for i in [0, 1, 2]:
for row in mat:
print row[i],
print
In real world, you should prefer builtin functions to complex flow statements.
The :func:`zip` function would do a great job for this use case::
>>> zip(*mat)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
See :ref:`tut-unpacking-arguments` for details on the asterisk in this line.
.. _tut-del:
The :keyword:`del` statement
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment