Python list_of_tuples:仅当元组的第一个值==某物时,才对每个元组的第二个值求和 [英] Python list_of_tuples: sum second val of each tuple, only if first val of tuple == something

查看:322
本文介绍了Python list_of_tuples:仅当元组的第一个值==某物时,才对每个元组的第二个值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个标记的"元组的列表...每个元组都在(tag_id,value)中,就像这样:

I have a list of "tagged" tuples...where each tuple is (tag_id, value)...like so:

my_list = [(tag_A, 100), (tag_A, 200), (tag_A, 300), (tag_A, 400), (tag_B, 400), (tag_B, 600)]

我想用相同的标签对每个元组的值求和...,以便:

I want to sum the values of each tuple with the same tag...so that:

sum_of_all_values_with_tag_A() = 1000

sum_of_all_values_with_tag_B() = 1000

我想不出一种简单的Pythonic方式.

I can't figure out a simple Pythonic way of doing that.

sum(set(value for tag_id, value in my_list)) 

...返回所有值的总和.

...returns the sum of ALL the values.

我想我可以用for或while循环将其包装起来,以便该表达式只触及我想求和的带有标签的元组...?我需要将与两个标签相关联的值相加...得出两个不同的总数,按上述方法进行区分.但是不能完全理解这种事情的优雅语法.

I suppose I can wrap that with a for or a while loop, so that only tuples with the tag I want to sum are touched by that expression...? I need to sum the values associated with both tags...resulting in two different totals, differentiated as above. But can't quite grok an elegant syntax for such a thing.

这是在预先存在的函数内部发生的.如果没有嵌套功能,那就太好了.

This is happening inside of a pre-existing function. Would be great to do it without nesting functions.

任何建议都值得赞赏!

推荐答案

方法

将数据放入defaultdict(list).总结一下.

from collections import defaultdict
my_list = [('tag_A', 100), ('tag_A', 200), ('tag_A', 300), ('tag_A', 400), ('tag_B', 400), ('tag_B', 600)]

d = defaultdict(list)
for tag, num in my_list:
    d[tag].append(num)

测试

>>> from collections import defaultdict
>>> my_list = [('tag_A', 100), ('tag_A', 200), ('tag_A', 300), ('tag_A', 400), ('tag_B', 400), ('tag_B', 600)]
>>> 
>>> d = defaultdict(list)
>>> for tag, num in my_list:
...     d[tag].append(num)
... 
>>> from pprint import pprint
>>> pprint(dict(d))
{'tag_A': [100, 200, 300, 400], 'tag_B': [400, 600]}
>>> 
>>> pprint({k: sum(v) for k, v in d.iteritems()})
{'tag_A': 1000, 'tag_B': 1000}

替代摘要例程

def summarize_by_tag(d):
    for k, v in d.iteritems():
        print k, sum(v)

>>> summarize_by_tag(d)
tag_A 1000
tag_B 1000

这篇关于Python list_of_tuples:仅当元组的第一个值==某物时,才对每个元组的第二个值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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