Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average of two consecutive elements in the list in Python

Tags:

python

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?

like image 648
drastega Avatar asked Dec 11 '13 18:12

drastega


People also ask

How do you find the average of a list element in Python?

In Python we can find the average of a list by simply using the sum() and len() function. sum() : Using sum() function we can get the sum of the list. len() : len() function is used to get the length or the number of elements in a list.

How do you find consecutive elements in a list?

We have to check whether it contains contiguous values or not. So, if the input is like nums = [6, 8, 3, 5, 4, 7], then the output will be true as the elements are 3, 4, 5, 6, 7, 8. otherwise, j := nums[i] - min_val.

How do you count the number of consecutive values in a list Python?

Just iterate elements in nums , and keep cnt to count the frequency of consecutive numbers.


1 Answers

data = [2.34, 3.45, 4.56, 1.23, 2.34, 7.89]
print [(a + b) / 2 for a, b in zip(data[::2], data[1::2])]

Explanation:

data[::2] is the elements 2.34, 4.56, 2.34

data[1::2] is the elements 3.45, 1.23, 7.89

zip combines them into 2-tuples: (2.34, 3.45), (4.56, 1.23), (2.34, 7.89)

like image 53
Paul Draper Avatar answered Sep 19 '22 23:09

Paul Draper