Question

So i have a particular array, that has 2 seperate arrays withing itself. What I am looking to do is to average together those 2 seperate arrays, so for instance, if i have my original array such as [(2,3,4),(4,5,6)] and I want an output array like [3,5], how would i do this? My attempt to do this is as follows:

averages = reduce(sum(array)/len(array), [array])
Was it helpful?

Solution 2

reduce is not a good choice here. Just use a list comprehension:

>>> a = [(2,3,4),(4,5,6)]
>>> [sum(t)/len(t) for t in a]
[3, 5]

Note that / is integer division by default in python2.

If you have numpy available, you have a nicer option:

>>> import numpy as np
>>> a = np.array(a)
>>> a.mean(axis=1)
array([ 3.,  5.])

OTHER TIPS

>>> map(lambda x: sum(x)/len(x), [(2,3,4),(4,5,6)])
[3, 5]

You can do this with a list comphrehesion:

data = [(2,3,4),(4,5,6)]
averages = [ sum(tup)/len(tup) for tup in data ]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top