gpt4 book ai didi

Python - 对元组列表进行分组和求和

转载 作者:太空狗 更新时间:2023-10-29 18:19:28 25 4
gpt4 key购买 nike

给定以下列表:

[
('A', '', Decimal('4.0000000000'), 1330, datetime.datetime(2012, 6, 8, 0, 0)),
('B', '', Decimal('31.0000000000'), 1330, datetime.datetime(2012, 6, 4, 0, 0)),
('AA', 'C', Decimal('31.0000000000'), 1330, datetime.datetime(2012, 5, 31, 0, 0)),
('B', '', Decimal('7.0000000000'), 1330, datetime.datetime(2012, 5, 24, 0, 0)),
('A', '', Decimal('21.0000000000'), 1330, datetime.datetime(2012, 5, 14, 0, 0))
]

我想按元组中的第一、第二、第四和第五列对它们进行分组,并对第三列求和。对于此示例,我将列命名为 col1、col2、col3、col4、col5。

在 SQL 中我会做这样的事情:

select col1, col2, sum(col3), col4, col5 from my table
group by col1, col2, col4, col5

是否有一种“很酷”的方式来做到这一点,还是完全是手动循环?

最佳答案

你想要itertools.groupby .

请注意,groupby 需要对输入进行排序,因此您可能需要事先进行排序:

keyfunc = lambda t: (t[0], t[1], t[3], t[4])
data.sort(key=keyfunc)
for key, rows in itertools.groupby(data, keyfunc):
print key, sum(r[2] for r in rows)

关于Python - 对元组列表进行分组和求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11058001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com