Python sum elements in 2d list with the same first value(Python sum 二维列表中具有相同第一个值的元素)
问题描述
我正在尝试找到一种有效的方法来执行以下操作:
I'm trying to find an efficient way to do the following:
我有这个样本:
并且需要
即将第一个元素相同的子列表的对应值相加.
i.e. sum the corresponding values of the sublists where the first element is the same.
非常感谢
我的代码是:
推荐答案
使用defaultdict
:
#driver 值:
由于输出的结构是这样的,我建议您使用 dict
类型来存储您的输出,因为将来处理它会更容易.
Since the output is structured as such, I would suggest you utilise the dict
type for storing your output as future processing with it will be easier.
如果您仍然希望输出为 list
,只需映射 dict
,如下所示:
In case you still want the output as a list
, just map the dict
, as follows:
这篇关于Python sum 二维列表中具有相同第一个值的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!