如何按常见项目对元组进行分组并找到每组的平均值

How to group tuples by common items and find average per each group(如何按常见项目对元组进行分组并找到每组的平均值)
本文介绍了如何按常见项目对元组进行分组并找到每组的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 data 的元组列表:

I have a list of tuples named data:

data = [('A', 2), 
        ('B', 2), ('B', 4), ('B', 6), ('B', 8), ('B', 6), ('B', 4), ('B', 3),
        ('C', 10), ('C', 10), ('C', 10),
        ('D', 12),
        ('E', 12),
        ('F', 10), ('F', 8), ('F', 6)]
average = []

我想要每个相同字母的平均值:

I would like an average of the values for each same letter:

预期输出:

average = [('A', 2), ('B', 5), ('C', 10), ('D', 12), ('E', 12), ('F', 8)]

推荐答案

试试 groupby

from itertools import groupby
data_ = [(n,[i[1] for i in g]) for n,g in groupby(data, key = lambda x:x[0])]   
result = [(i,float(sum(j))/float(len(j))) for i,j in data_]

结果

[('A', 2.0),
 ('B', 4.714285714285714),
 ('C', 10.0),
 ('D', 12.0),
 ('E', 12.0),
 ('F', 8.0)]

这篇关于如何按常见项目对元组进行分组并找到每组的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)