Antlafe
Antlafe

Reputation: 43

Computing mean per slices in Python

I have an array :

A = [2,6,4,3,6,9,4,6,5]

Is there an elegant (1-2 lines, no loop) and pythonic way to compute the mean per blocks of 3 elements per 3 elements of A.

In order to obtain B :

B = [4,6,3] = [mean([2,6,4]),mean([3,6,9]),mean([4,6,5])

Upvotes: 0

Views: 56

Answers (3)

Ma0
Ma0

Reputation: 15204

No there is no "elegant" way that does not use a loop. Unless you limit your definition of loop to the for keyword. Calling sum or map for instance also uses a loop.

So, refuse this absurd requirement and write some clean code instead.

A = [2,6,4,3,6,9,4,6,5]
n = 3

def mean(g):
  return sum(g) / len(g)

res = [mean(A[n*i:n*(i+1)]) for i in range(0, len(A)//n)]
print(res)  # -> [4.0, 6.0, 5.0]

Upvotes: 0

zipa
zipa

Reputation: 27879

In one line it would look like this:

B = [sum(A[i:i+3])/3 for i in range(0, len(A), 3)]

Upvotes: 1

Zoe
Zoe

Reputation: 1410

You can use list comprehension, but it still includes an internal loop.

B = [np.mean([A[i],A[i+1],A[i+2]]) for i in np.arange(0, len(A),3)]

Upvotes: 0

Related Questions