在 Python 中以格式 (string, value) 获取列表中每个元组的值的平均值

我有一个元组列表,例如:(A, 1), (B, 2), (C, 3), (A, 9), (B, 8).

如何在不知道元组第一个元素的出现次数的情况下,获取元组第一个元素的每个值的平均值?

我想要这样的东西:

(A, 5), (B, 5), (C, 3).


鸿蒙传说
浏览 188回答 2
2回答

MMMHUHU

使用groupby和itemgetter:from itertools import groupbyfrom operator import itemgetterfrom statistics import means = [('A', 1), ('B', 2), ('C', 3), ('A', 9), ('B', 8)]s2 = sorted(s, key=itemgetter(0))   # sorting the tuple based on 0th indexprint([(k, int(mean(list(zip(*g))[1]))) for k, g in groupby(s2, itemgetter(0))])输出:[('A', 5), ('B', 5), ('C', 3)]

qq_花开花谢_0

from collections import defaultdictsample = [("A", 1), ("B", 2), ("C", 3), ("A", 9), ("B", 8)]store_alphabet_count = defaultdict(list)for alphabet, count in sample:    store_alphabet_count[alphabet].append(count)result = [    (key, sum(value) // len(value)) for key, value in store_alphabet_count.items()]print(result)输出:[('A', 5), ('B', 5), ('C', 3)]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python