使用 Python 为元组中每个给定的第一个值求和元组中的第二个值 [英] Sum second value in tuple for each given first value in tuples using Python
问题描述
我正在处理大量记录,需要对每个客户帐户的给定字段求和,以达到帐户总体余额.虽然我可以将数据以任何合理的形式放置,但我认为最简单的方法是在处理每条记录时使用元组列表 (cust_id,balance_contribution).经过一轮处理后,我想为每个 cust_id 添加第二项,并且我试图在不循环数千次数据的情况下进行.
I'm working with a large set of records and need to sum a given field for each customer account to reach an overall account balance. While I can probably put the data in any reasonable form, I figured the easiest would be a list of tuples (cust_id,balance_contribution) as I process through each record. After the round of processing, I'd like to add up the second item for each cust_id, and I am trying to do it without looping though the data thousands of time.
例如,输入数据可能如下所示:[(1,125.50),(2,30.00),(1,24.50),(1,-25.00),(2,20.00)]
As an example, the input data could look like:[(1,125.50),(2,30.00),(1,24.50),(1,-25.00),(2,20.00)]
我希望输出是这样的:
[(1,125.00),(2,50.00)]
我读过其他问题,其中人们只是想使用 sum(i for i, j in a) 的形式添加元组的第二个元素的值,但这确实通过第一个元素将它们分开.
I've read other questions where people have just wanted to add the values of the second element of the tuple using the form of sum(i for i, j in a), but that does separate them by the first element.
本次讨论,python sum tuple list based on tuple firstvalue,它将值作为分配给字典中的每个键 (cust_id) 的列表.我想我可以弄清楚如何在列表中添加每个值?
This discussion, python sum tuple list based on tuple first value, which puts the values as a list assigned to each key (cust_id) in a dictionary. I suppose then I could figure out how to add each of the values in a list?
有没有更好的方法来解决这个问题?
Any thoughts on a better approach to this?
提前致谢.
推荐答案
import collections
def total(records):
dct = collections.defaultdict(int)
for cust_id, contrib in records:
dct[cust_id] += contrib
return dct.items()
这篇关于使用 Python 为元组中每个给定的第一个值求和元组中的第二个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!