- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Average of each n-length consecutive segment in a Python list
We have a list containing only numbers. We plan to get the average of a set of sequential numbers from the list which keeps rolling from the first number to next number and then to next number and so on.
Example
The below example simplifies the requirement of finding the average of each 4-length consecutive elements of the list.
Given list: [10,12,14,16,18,20,22,24,26] Average of every segment of 4 consecutive numbers: [13.0, 15.0, 17.0, 19.0, 21.0, 23.0]
With sum and range
We use the list comprehension approach to take the sum of the consecutive numbers by applying range to keep track of how many numbers we gathered. Then we keep dividing the sum with the segment length with the help of a loop. Finally the result is gathered into a new list.
Example
listA = [10,12,14,16,18,20,22,24,26] print("Given list:\n",listA) seg = 4 # List comprehension res = [sum(listA[m:m + seg])/seg for m in range(len(listA) - seg + 1)] print("new list with averages:\n ",res)
Running the above code gives us the following result −
Given list: [10, 12, 14, 16, 18, 20, 22, 24, 26] new list with averages: [13.0, 15.0, 17.0, 19.0, 21.0, 23.0]
With islice and mean
In this approach we take help of python modules which can calculate these values in a more direct way. We keep slicing the elements of the list in the given range using the isslice function and then apply the mean function directly on the new list to get the final result.
Example
from statistics import mean from itertools import islice listA = [10,12,14,16,18,20,22,24,26] print("Given list:\n",listA) # With islice and mean listB = zip(*(islice(listA, i, None) for i in range(4))) res = list(map(mean, listB)) print("new list with averages:\n ",res)
Output
Running the above code gives us the following result −
Given list: [10, 12, 14, 16, 18, 20, 22, 24, 26] new list with averages: [13, 15, 17, 19, 21, 23]