Skip to content
Related Articles

Related Articles

Python | Record elements Average in List
  • Last Updated : 10 Feb, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

Resultant list of tuples: [('Akshat', 7.333333333333333), ('Garg', 9.5)]

Method #2: Converting into dictionary



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

Resultant list of tuples: [('Garg', 9.5), ('Akshat', 7.333333333333333)]

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :