[Tutor] How to sum rows and columns of a matrix?

Gregor Lingl glingl at aon.at
Mon Jan 31 19:09:59 CET 2005


Hi all of you,

I'm representing a 4x4 matrix as a 16-element list, e.g.

m=range(16)

first 4 elements first row, second four elements second row etc.
I want to sum rows and columns like

i-th row:

sum(m[4*i:4*i+4])

and ith column:

sum(m[i::4])

This seems to be slow because of the formation of the slices.
I wonder if there is a way using generators or generator-expressions
(which I didn't study yet) to compute these sums without copying
parts of the matrix to a new list. (I'd guess that there should exist
some canonical generator for sequences, which produces their elements 
..., maybe also for slices ?)

All comments, hints, solutions are welcome.

Regards,
Gregor

-- 
Gregor Lingl
Reisnerstrasse 3/19
A-1030 Wien

Telefon: +43 1 713 33 98
Mobil:   +43 664 140 35 27

Autor von "Python für Kids"
Website: python4kids.net


More information about the Tutor mailing list