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?
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.
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.
Just iterate elements in nums , and keep cnt to count the frequency of consecutive numbers.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With