Average of two consecutive elements in the list in Python

Viewed 13485

I have a list of even number of float numbers:

[2.34, 3.45, 4.56, 1.23, 2.34, 7.89, ...].

My task is to calculate average of 1 and 2 elements, 3 and 4, 5 and 6, etc. What is the short way to do this in Python?

5 Answers

Using NumPy to find the mean/average of consecutive two values this is more efficient in terms of Time and Space Complexity:

data=np.array([1,2,3,4,5,6])
k=2 #In your case
data1=np.mean(data.reshape(-1, k), axis=1)
Related