King Awan
King Awan

Reputation: 3

how to traverse the given list and find average of second index of tuples and store in a new list in python

I know this is a silly question but I'm new in python and don't know how to do it. Actually I have retrieved some data from mysql database and got that as following list.

[
    (7, 80),
    (7, 40),
    (7, 100),
    (34, 100),
    (34, 20),
    (36, 60),
    (36, 40),
    (36, 100),
    (36, 60),
]

The name of list is "norm_rating". in every tuple like (7,80) the first element is "id" and second element is normalized value of "rating". What I want is to get a new list in which I will have 1 unique entry of every "id" and average of rating from the "norm_rating" list. Like I want new list to be,

[(7, 73.3), (34, 60), (36, 65)]

can I please have a python code for this.

Upvotes: 0

Views: 60

Answers (1)

Samwise
Samwise

Reputation: 71522

I'd use itertools.groupby to group the tuples with the same first element, and then just use statistics.mean to get the average of the second elements:

>>> data = [(7, 80), (7, 40), (7, 100), (34, 100), (34, 20), (36, 60), (36, 40), (36, 100), (36, 60)]
>>> from itertools import groupby
>>> from statistics import mean
>>> [(n, mean(t[1] for t in group)) for n, group in groupby(data, lambda t: t[0])]
[(7, 73.33333333333333), (34, 60), (36, 65)]

Upvotes: 1

Related Questions