On Sat, Dec 1, 2012 at 9:40 AM, richard kappler <richkapp...@gmail.com> wrote: > 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 >
The way you are trying to do it would be >>> revdiag = [M[i][j] for i,j in [(0,2),(1,1),(2,0)]] _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor