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