Python | Mean of consecutive Sublist
Last Updated :
24 Mar, 2023
Some of the classical problems in programming domain comes from different categories and one among them is finding the mean of subsets. This particular problem is also common when we need to compute the average and store consecutive group mean. Let’s try different approaches to this problem in python language.
Method #1 : Using list comprehension + sum() The list comprehension can be used to perform the this particular task to filter out successive groups and sum function can be used to get the summation of the filtered solution. We divide the sum by sublist size for average.
Python3
test_list = [ 4 , 7 , 8 , 10 , 12 , 15 , 13 , 17 , 14 ]
print ("The original list : " + str (test_list))
res = [ sum (test_list[x : x + 3 ]) / 3 for x in range ( 0 , len (test_list), 3 )]
print ("The grouped average list is : " + str (res))
|
Output :
The original list : [4, 7, 8, 10, 12, 15, 13, 17, 14]
The grouped average list is : [6.333333333333333, 12.333333333333334, 14.666666666666666]
Time Complexity: O(n), where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “test_list”.
Method #2 : Using sum() + itertools.islice() The task of slicing the list into chunks is done by islice method here and the conventional task of getting the summation is done by the sum function as the above method. We divide the sum by sublist size for average.
Python3
import itertools
test_list = [ 4 , 7 , 8 , 10 , 12 , 15 , 13 , 17 , 14 ]
print ("The original list : " + str (test_list))
res = [ sum ( list (itertools.islice(test_list, i, i + 3 ))) / 3 for i in range ( 0 , len (test_list), 3 )]
print ("The grouped average list is : " + str (res))
|
Output :
The original list : [4, 7, 8, 10, 12, 15, 13, 17, 14]
The grouped average list is : [6.333333333333333, 12.333333333333334, 14.666666666666666]
Time complexity: O(n), where n is the length of the input list ‘test_list’
Space complexity: O(n), where n is the length of the input list ‘test_list’
Method #3 : Using numpy.mean()
We can use the mean function from numpy library which will help us to get the mean of elements. We pass the argument list converted to numpy array and chunksize as argument to mean function.
Python3
import numpy as np
test_list = [ 4 , 7 , 8 , 10 , 12 , 15 , 13 , 17 , 14 ]
print ( "The original list : " + str (test_list))
res = [np.mean(np.array(test_list[i:i + 3 ])) for i in range ( 0 , len (test_list), 3 )]
print ( "The grouped average list is : " + str (res))
|
Output:
The original list : [4, 7, 8, 10, 12, 15, 13, 17, 14]
The grouped average list is : [6.333333333333333, 12.333333333333334, 14.666666666666666]
Time complexity: O(n)
Space complexity: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...