简体   繁体   English

以 Python 中的格式(字符串,值)获取列表中每个元组的平均值

[英]Get mean of values for each tuple in a list in the format (string, value) in Python

I have a list of tuples like: (A, 1), (B, 2), (C, 3), (A, 9), (B, 8) .我有一个元组列表,例如: (A, 1), (B, 2), (C, 3), (A, 9), (B, 8)

How to get the mean of each value referred to the first element of the tuples, not knowing the number of occurences of the first element of tuples?如何在不知道元组第一个元素的出现次数的情况下获得每个值的平均值?

I want something like:我想要类似的东西:

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

from collections import defaultdict

sample = [("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)

Output: Output:

[('A', 5), ('B', 5), ('C', 3)]

Using groupby and itemgetter :使用groupbyitemgetter

from itertools import groupby
from operator import itemgetter
from statistics import mean


s = [('A', 1), ('B', 2), ('C', 3), ('A', 9), ('B', 8)]
s2 = sorted(s, key=itemgetter(0))   # sorting the tuple based on 0th index

print([(k, int(mean(list(zip(*g))[1]))) for k, g in groupby(s2, itemgetter(0))])

OUTPUT: OUTPUT:

[('A', 5), ('B', 5), ('C', 3)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM