Python | Record elements Average in List
Last Updated :
17 Apr, 2023
Given a list of tuples, write a program to find average of similar tuples in list.
Examples:
Input:
[('Geeks', 10), ('For', 10), ('Geeks', 2), ('For', 9), ('Geeks', 10)]
Output:
Resultant list of tuples: [('For', 9.5), ('Geeks', 7.333333333333333)]
Input:
[('Akshat', 10), ('Garg', 10), ('Akshat', 2), ('Garg', 9), ('Akshat', 10)]
Output:
Resultant list of tuples: [('Akshat', 7.333333333333333), ('Garg', 9.5)]
Method #1: Using List Comprehension
Python3
ini_list = [( 'Akshat' , 10 ), ( 'Garg' , 10 ), ( 'Akshat' , 2 ),
( 'Garg' , 9 ), ( 'Akshat' , 10 )]
def avg(l):
return sum (l) / len (l)
result = [(n, avg([v[ 1 ] for v in ini_list
if v[ 0 ] is n])) for n in set ([n[ 0 ] for n in ini_list])]
print ("Resultant list of tuples: {}". format (result))
|
Output:
Resultant list of tuples: [('Akshat', 7.333333333333333), ('Garg', 9.5)]
Time Complexity: O(n)
Auxiliary Space: O(n), where n is length of list.
Method #2: Converting into dictionary
Python3
ini_list = [( 'Akshat' , 10 ), ( 'Garg' , 10 ), ( 'Akshat' , 2 ),
( 'Garg' , 9 ), ( 'Akshat' , 10 )]
temp_dict = dict ()
for tuple in ini_list:
key, val = tuple
temp_dict.setdefault(key, []).append(val)
result = []
for name, values in temp_dict.items():
result.append((name, ( sum (values) / len (values))))
print ("Resultant list of tuples: {}". format (result))
|
Output:
Resultant list of tuples: [('Garg', 9.5), ('Akshat', 7.333333333333333)]
Time Complexity: O(n), where n is the number of elements in the list “ini_list”.
Auxiliary Space: O(n), where n is the number of elements in the list “ini_list”.
Method #3: Using Defaultdict
Python3
from collections import defaultdict
ini_list = [( 'Akshat' , 10 ), ( 'Garg' , 10 ), ( 'Akshat' , 2 ),
( 'Garg' , 9 ), ( 'Akshat' , 10 )]
result = defaultdict( list )
for name, value in ini_list:
result[name].append(value)
output = [(key, sum (value) / len (value)) for key, value in result.items()]
print ( "Resultant list of tuples: {}" . format (output))
|
Output
Resultant list of tuples: [('Akshat', 7.333333333333333), ('Garg', 9.5)]
Time complexity: O(n)
Auxiliary Space: O(n)
Method 4: use the pandas library in Python
step-by-step approach:
Import the pandas library.
Create a DataFrame from the initial list of tuples.
Group the DataFrame by the first column (name).
Calculate the mean of the second column (value) for each group.
Reset the index of the resulting DataFrame to convert the group name from the index to a column.
Convert the resulting DataFrame to a list of tuples.
Python3
import pandas as pd
ini_list = [( 'Akshat' , 10 ), ( 'Garg' , 10 ), ( 'Akshat' , 2 ),
( 'Garg' , 9 ), ( 'Akshat' , 10 )]
df = pd.DataFrame(ini_list, columns = [ 'name' , 'value' ])
result_df = df.groupby( 'name' )[ 'value' ].mean().reset_index()
result = [ tuple (x) for x in result_df.to_numpy()]
print ( "Resultant list of tuples:" , result)
|
Output:
Resultant list of tuples: [('Akshat', 7.333333333333333), ('Garg', 9.5)]
time complexity of this approach is O(n log n), where n is the number of tuples in the initial list. The auxiliary space complexity is O(n), as the DataFrame and resulting list both require space proportional to the number of tuples in the initial list.
Share your thoughts in the comments
Please Login to comment...