如何遍历给定列表并找到元组的第二个索引的平均值并存储在 python 中的新列表中

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

我知道这是个愚蠢的问题,但我是 python 的新手,不知道该怎么做。实际上我已经从 mysql 数据库中检索了一些数据并得到了如下列表。

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

列表的名称是“norm_rating”。在像 (7,80) 这样的每个元组中,第一个元素是“id”,第二个元素是“rating”的规范化值。我想要的是获得一个新列表,其中我将拥有每个“id”的 1 个唯一条目和“norm_rating”列表中的平均评分。就像我想要的新列表一样,

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

请给我一个 python 代码。

我会使用 itertools.groupby 将具有相同第一个元素的元组分组,然后只使用 statistics.mean 获取第二个元素的平均值:

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