Like a matrix

Robert Brewer fumanchu at amor.org
Sun Oct 26 03:48:35 EST 2003


Yazar Yolait wrote:
> I have a string of numbers in a file like so:
> 0 3 23.3 352 45 4
> 4 45 23 54 4 5.4 .6
> 
> I need to average them horizontally and vertically.  
> Horizontally is easy
> since I'm reading one line at a time, but how can I do it 
> vertically like 0
> and 4, 3 and 45, etc.
> I was thinking of a dictionary but how do you add entries to 
> a dictionary,
> you can't can you?  Like I would add 0 to a dictionary that 
> holds the 0th
> column.  And then when I get to line 2, I would add 4 to the 
> dictionary
> which has the 0th column data.

>>> a = [0, 3, 23.3, 352, 45, 4]
>>> b = [4, 45, 23, 54, 4, 5.4, .6]
>>> reduce(lambda x, y: x + y, a) / len(a)    # Horizontal avg
71.216666666666669
>>> reduce(lambda x, y: x + y, b) / len(b)    # Horizontal avg
19.428571428571427
>>> g = zip(a, b)
>>> g
[(0, 4), (3, 45), (23.300000000000001, 23), (352, 54), (45, 4), (4,
5.4000000000000004)]
>>> [reduce(lambda x, y: x + y, eachColumn) for eachColumn in g]
[4, 48, 46.299999999999997, 406, 49, 9.4000000000000004]
>>> [reduce(lambda x, y: x + y, eachColumn) / len(eachColumn) for
eachColumn in g]
[2, 24, 23.149999999999999, 203, 24, 4.7000000000000002]

Last line is a list of vertical averages. You could perform a list of
horizontal averages the same way, with:

>>> [reduce(lambda x, y: x + y, eachRow) / len(eachRow) for eachRow in
(a, b)]
[71.216666666666669, 19.428571428571427]


Robert Brewer, who needed a break from database connectors in a big way,
MIS
Amor Ministries
fumanchu at amor.org





More information about the Python-list mailing list