Open In App

Python | Record elements Average in List

Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python code to demonstrate
# find average of similar tuples in list
 
# initialising list of tuples
ini_list = [('Akshat', 10), ('Garg', 10), ('Akshat', 2),
                            ('Garg', 9), ('Akshat', 10)]
 
# finding average of similar entries
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])]
 
# printing result
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




# Python code to demonstrate
# find average of similar tuples in list
 
# initialising list of tuples
ini_list = [('Akshat', 10), ('Garg', 10), ('Akshat', 2),
                            ('Garg', 9), ('Akshat', 10)]
 
# finding average of similar entries
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))))
 
# printing result
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
 
# initializing list of tuples
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()]
 
# printing result
print("Resultant list of tuples: {}".format(output))
#This code is contributed by Edula Vinay Kumar Reddy


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
 
# initialising list of tuples
ini_list = [('Akshat', 10), ('Garg', 10), ('Akshat', 2),
            ('Garg', 9), ('Akshat', 10)]
 
# creating a DataFrame from the initial list of tuples
df = pd.DataFrame(ini_list, columns=['name', 'value'])
 
# calculating the mean of the 'value' column for each 'name' group
result_df = df.groupby('name')['value'].mean().reset_index()
 
# converting the resulting DataFrame to a list of tuples
result = [tuple(x) for x in result_df.to_numpy()]
 
# printing the result
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.



Last Updated : 17 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads