Change language

Python | Average of each n-length consecutive segment in the list

Example :

  Input:  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 , 12, 13, 14, 15, 16, 17, 18, 19, 20]  Output:  [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 , 14, 15, 16, 17, 18]  Explanation:  Segment 1 - [1, 2, 3, 4, 5] =" 15/5 = 3 Segment 2 - [2, 3, 4, 5, 6] =" 20/5 = 4 Segment 3 - [3, 4, 5, 6, 7] =" 25/5 = 5 and so on ..... 

Method # 1: Using List Comprehension

# Python code to find the average of each sequential segment

  
# Initialization List

Input = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ,

12 , 13 , 14 , 15 , 16 , 17 , 18 , 19 , 20 ]

  
# Define splits

splits = 5

 
# Find the average for each sequential segment

Output = [ sum ( Input [i: i + splits]) / splits

for i in range ( len ( Input ) - splits + 1 )]

  
# output n and printing

print (Output)

Exit:

[3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0]

Method # 2: Using mean functions

# Python code to find the average of each sequential segment

  
# Import

from statistics import mean

from itertools import islice

  # Initialization list

Input = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ,

12 , 13 , 14  , 15 , 16 , 17 , 18 , 19 , 20 ]

 
# Find the average for each consecutive segment

zip_list = zip ( * (islice ( Input , i, None ) for i in range ( 5 )))

Output = list ( map ( mean , zip_list))

 
# output to print

print (Output)

Exit:

[3, 4, 5, 6, 7, 8, 9 , 10, 11, 12, 13, 14, 15, 16, 17, 18]

Shop

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Best laptop for engineering student

$

Best laptop for development

$

Best laptop for Cricut Maker

$

Best laptop for hacking

$890

Best laptop for Machine Learning

$950

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method