[Tutor] reverse diagonal
richard kappler
richkappler at gmail.com
Sat Dec 1 16:40:50 CET 2012
I'm working through Mark Lutz's "Python," reviewing the section on lists. I
understand the list comprehension so far, but ran into a snag with the
matrix. I've created the matrix M as follows:
M = [[1, 2, 3[, [4, 5, 6], [7, 8, 9]]
then ran through the various comprehension examples, including:
diag = [M[i][i] for i in [0, 1, 2]]
which, of course, gave me [1, 5, 9].
Then I tried creating revdiag, wanting to return [3, 5, 7], tried several
different ways, never quite got what I was looking for, so I'm looking for
guidance as I'm stuck on this idea. Here's the various attempts I made and
the tracebacks:
>>> revdiag = [M[i][i] for i in [2, 1, 0]]
>>> revdiag
[9, 5, 1]
# once I saw the output, this one made sense to me.
>>> revdiag = [M[i][j] for i in [0, 1, 2] and for j in [2, 1, 0]]
File "<stdin>", line 1
revdiag = [M[i][j] for i in [0, 1, 2] and for j in [2, 1, 0]]
^
SyntaxError: invalid syntax
>>> revdiag = [M[i][j] for i in [0, 1, 2] and j in [2, 1, 0]]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'j' is not defined
>>> revdiag = [M[i][j] for i in [0, 1, 2], for j in [2, 1, 0]]
File "<stdin>", line 1
revdiag = [M[i][j] for i in [0, 1, 2], for j in [2, 1, 0]]
^
SyntaxError: invalid syntax
>>> revdiag = [M[i][j] for i in [0, 1, 2], and for j in [2, 1, 0]]
File "<stdin>", line 1
revdiag = [M[i][j] for i in [0, 1, 2], and for j in [2, 1, 0]]
^
SyntaxError: invalid syntax
I see where the errors are occurring, but I'm not sure I fully understand
why they are occurring or how to get what I'm looking for with what I
presently know, which admittedly is not much. Any help would be appreciated.
regards, Richard
--
quando omni flunkus moritati
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20121201/90fb23c3/attachment.html>
More information about the Tutor
mailing list