[Tutor] reverse diagonal

Dave Angel d at davea.name
Sun Dec 2 02:12:07 CET 2012


On 12/01/2012 11:28 AM, Brian van den Broek wrote:
> On 1 December 2012 10:40, richard kappler <richkappler at 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:
>
> Richard,
>
> It is good you copy and pasted everything I snipped. But, you typed in
> the line defining M. Better to also copy paste that, as you typed it
> in wrong :-)
>
> Here's one way that assumes of M only that it is an n-by-n matrix:
>
>>>> M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>>> for i in reversed(range(len(M))):
> 	M[i][i]
>
> 	
> 9
> 5
> 1
>

The only catch to that is it's not what he wants.  He said he wants 3, 5, 7

-- 
DaveA


More information about the Tutor mailing list