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
# 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
OutputResultant 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.
Similar Reads
Python - Rear elements Average in List
Sometimes, while working with data, we can have a problem in which we need to perform the mean of all the rear elements that come after K. This can be an application in Mathematics and Data Science domain. Let us discuss certain ways in which this task can be performed. Method #1 : Using sum() + li
6 min read
Column Average in Record List - Python
Given a list of records where each record contains multiple fields, the task is to compute the average of a specific column. Each record is represented as a dictionary or a list, and the goal is to extract values from the chosen column and calculate their average. Letâs explore different methods to
3 min read
Update Each Element in Tuple List - Python
The task of updating each element in a tuple list in Python involves adding a specific value to every element within each tuple in a list of tuples. This is commonly needed when adjusting numerical data stored in a structured format like tuples inside lists. For example, given a = [(1, 3, 4), (2, 4,
3 min read
Python | Average String length in list
Sometimes, while working with data, we can have a problem in which we need to gather information of average length of String data in list. This kind of information might be useful in Data Science domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehen
8 min read
Python - Average digits count in a List
Given a list of elements extract the average digit count in List. Input : test_list = [34, 2345, 23, 456, 2, 23, 456787] Output : 2.857142857142857 Explanation : Average of all digit count. [2+4+2+3+1+2+6 = 20, 20/7 = 2.857142857142857] Input : test_list = [34, 1, 456]Output : 2.0 Explanation : Aver
4 min read
Python - Operation to each element in list
Given a list, there are often when performing a specific operation on each element is necessary. While using loops is a straightforward approach, Python provides several concise and efficient methods to achieve this. In this article, we will explore different operations for each element in the list.
2 min read
Python - Elements Lengths in List
Sometimes, while working with Python lists, can have problem in which we need to count the sizes of elements that are part of lists. This is because list can allow different element types to be its members. This kind of problem can have application in many domains such has day-day programming and we
6 min read
Find Sum and Average of List in Python
Our goal is to find sum and average of List in Python. The simplest way to do is by using a built-in method sum() and len(). For example, list of numbers is, [10, 20, 30, 40, 50] the sum is the total of all these numbers and the average is the sum divided by the number of elements in the list.Using
2 min read
Python | Get Top N elements from Records
Sometimes, while working with data, we can have a problem in which we have records and we require to find the highest N scores from it. This kind of application is popular in web development domain. Let's discuss certain ways in which this problem can be solved. Method #1 : Using sorted() + lambda T
5 min read
Python | Average of two lists
The problem of finding a average values in a list is quite common. But sometimes this problem can be extended in two lists and hence becomes a modified problem. This article discusses shorthands by which this task can be performed easily. Letâs discuss certain ways in which this problem can be solve
5 min read