python两个元组相加,Python list_of_tuples:仅当元组的第一个值==某物时,才对每个元组的第二个值求和...

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

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.

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.

Any suggestions are appreciated!

解决方案

Approach

Put your data into a defaultdict(list). Summarize that.

Code

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)

Test

>>> 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}

Alternative summary routine

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

  • 0
    点赞
  • 0
    收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:游动-白 设计师:我叫白小胖 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值