On 12/01/2012 10:40 AM, richard kappler 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]] There's an obvious typo in that line. You really need to copy/paste into a message, since some retyping errors could seriously mislead us. > 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 > There's no such syntax. If you want to assign two variables, then use tuple-unpacking, like:
revdiag = [M[i][j] for i,j in [(0,2), (1,1), (2,0)]] Or even better: revdiag = [M[i][2-i] for i in [0, 1, 2]] Notice I compute the j value, since it's very dependent on i or even revdiag = [M[i][len(M)-1-i] for i in range(len(M)) ] which would still work for other sizes of M (All my code untested, as I have just run out of time) -- DaveA _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor