Like a matrix

Peter Otten __peter__ at web.de
Sun Oct 26 12:06:07 CET 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.

>>> from __future__ import division
>>> def avg(alist): return sum(alist)/len(alist)
...
>>> u = [1,2,3]
>>> v = [3,2,1]
>>> avg(u)
2.0

So that was the easy part. Now let's create the columns:

>>> m, n, o = zip(u, v)
>>> m
(1, 3)
>>> n
(2, 2)
>>> avg(o)
2.0
>>>

So that wasn't particular hard, now you see it :-)
zip() returns tuples instead of lists, but as you see above that does no
harm.

Peter





More information about the Python-list mailing list