如何在元组列表中找到每个相似条目的平均值? [英] How can I find the average of each similar entry in a list of tuples?

查看:68
本文介绍了如何在元组列表中找到每个相似条目的平均值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个元组列表

[('Jem', 10), ('Sam', 10), ('Sam', 2), ('Jem', 9), ('Jem', 10)]

我如何找到每个名字加上数字的平均值,即用Jem存储在元组中的所有数字的平均值,然后输出它们?在此示例中,输出为:

How do I find the average of the numbers coupled with each name, i.e. the average of all the numbers stored in a tuple with Jem, and then output them? In this example, the output would be:

Jem 9.66666666667
Sam 6

推荐答案

有两种方法可以做到这一点.一种很简单,一种很漂亮.

There's a couple ways to do this. One is easy, one is pretty.

使用字典!构建for循环很容易,它遍历了元组并将第二个元素附加到字典中,并在第一个元素上键入内容.

Use a dictionary! It's easy to build a for loop that goes through your tuples and appends the second element to a dictionary, keyed on the first element.

d = {}
tuples = [('Jem', 10), ('Sam', 10), ('Sam', 2), ('Jem', 9), ('Jem', 10)]
for tuple in tuples:
    key,val = tuple
    d.setdefault(key, []).append(val)

一旦它在字典中,您可以执行以下操作:

Once it's in a dictionary, you can do:

for name, values in d.items():
    print("{name} {avg}".format(name=name, avg=sum(values)/len(values)))

漂亮:

使用itertools.groupby.仅当您的数据按要分组的键排序时才有效(在这种情况下,对于tuples中的每个tt[0]),因此在这种情况下并不理想,但这是突出显示功能.

Pretty:

Use itertools.groupby. This only works if your data is sorted by the key you want to group by (in this case, t[0] for each t in tuples) so it's not ideal in this case, but it's a nice way to highlight the function.

from itertools import groupby

tuples = [('Jem', 10), ('Sam', 10), ('Sam', 2), ('Jem', 9), ('Jem', 10)]
tuples.sort(key=lambda tup: tup[0])
# tuples is now [('Jem', 10), ('Jem', 9), ('Jem', 10), ('Sam', 10), ('Sam', 2)]

groups = groupby(tuples, lambda tup: tup[0])

这将构建一个看起来像这样的结构:

This builds a structure that looks kind of like:

[('Jem', [('Jem', 10), ('Jem', 9), ('Jem', 10)]),
 ('Sam', [('Sam', 10), ('Sam', 2)])]

我们可以使用它来建立我们的名称和平均值:

We can use that to build our names and averages:

for groupname, grouptuples in groups:
    values = [t[1] for t in groupvalues]
    print("{name} {avg}".format(name=groupname, avg=sum(values)/len(values)))

这篇关于如何在元组列表中找到每个相似条目的平均值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆