[英]Python list_of_tuples: sum second val of each tuple, only if first val of tuple == something
I have a list of "tagged" tuples...where each tuple is (tag_id, value)...like so: 我有一个“标记”元组列表...每个元组都是(tag_id,value)...就像这样:
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. 我无法想出一个简单的Pythonic方法。
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...? 我想我可以用for或while循环来包装它,这样只有那个带有我想要求和的标签的元组被这个表达式触及......? 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! 任何建议表示赞赏!
Use a generator expression to sum per tag: 使用生成器表达式对每个标记求和:
sum(val for tag, val in my_list if tag == tag_A)
You could sort on the tags then use itertools.groupby
to create per-tag groups and sums: 您可以对标记进行排序 ,然后使用
itertools.groupby
创建每个标记组和总和:
from itertools import groupby
from operator import itemgetter
key = itemgetter(0) # tag
sums = {tag: sum(tup[1] for tup in group)
for tag, group in groupby(sorted(my_list, key=key), key=key)}
This would produce a dictionary mapping tags to per-tag sum: 这将产生一个字典映射标签到每个标签总和:
>>> from itertools import groupby
>>> from operator import itemgetter
>>> tag_A, tag_B = 'A', 'B'
>>> my_list = [(tag_A, 100), (tag_A, 200), (tag_A, 300), (tag_A, 400), (tag_B, 400), (tag_B, 600)]
>>> key = itemgetter(0) # tag
>>> sums = {tag: sum(tup[1] for tup in group)
... for tag, group in groupby(sorted(my_list, key=key), key=key)}
>>> print sums
{'A': 1000, 'B': 1000}
Put your data into a defaultdict(list)
. 将您的数据放入
defaultdict(list)
。 Summarize that. 总结一下。
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
As in other answers I would just use the defaultdict
but unless you need the groups again later. 和其他答案一样,我只会使用
defaultdict
但除非你以后再次需要这些组。 Just sum them as you group. 只要在分组时加以总结即可。 my_list could then be a very large iterable and you're not storing the whole thing in memory.
my_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)]
result = defaultdict(int)
for tag, value in my_list:
result[tag] += value
print result
defaultdict(<type 'int'>, {'tag_A': 1000, 'tag_B': 1000})
without importing anything. 没有进口任何东西 .
。
mysum={}
my_list = [('tag_A', 100), ('tag_A', 200), ('tag_A', 300), ('tag_A', 400), ('tag_B', 400), ('tag_B', 600)]
for x in my_list:
mysum.setdefault(x[0],0)
mysum[x[0]]+=x[1]
print mysum
output:: 输出::
{'tag_A': 1000, 'tag_B': 1000}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.