Python:列表加法

标签 python list add

我有两个如下所示的列表。我正在从数据库中获取它

EmpID = Assign.objects.select_related().filter(pName=selProject).filter()
    .order_by('laEmpNum').values_list('laEmpNum', flat=True)

TotDur = Assign.objects.select_related().filter(pName=selProject).order_by('laEmpNum')
    .values_list('duration', flat=True)

EmpID = [u'1046', u'1046', u'1046', u'8008', u'8008', u'8011'] 

TotDur = [0.0, 2.0, 2.5, 0.0, 2.7, 1.2] 

如果 EmpID 相同,则 TotDur 中的相应值应收集并相加(求和)。

ResOne = 0.0 + 2.0 + 2.5    i.e 4.5
ResTwo = 0.0+2.7            i.e 2.7
ResThr = 1.2                i.e 1.2

如何在 Python 中执行此操作。

最佳答案

defaultdict是一个很好用的数据结构,对于 int 字段,它假定新键的值为 0,并允许轻松收集桶:

from collections import defaultdict
d = defaultdict(int)
for i, j in zip(EmpID, TotDur):
    d[i] += j
print d # defaultdict(<type 'int'>, {u'8008': 2.7, u'1046': 4.5, u'8011': 1.2})

关于Python:列表加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13429332/

相关文章:

python - 保持可变元素的排序列表是最新的

facebook - "Add to my page"应用链接丢失

python - 模板中的 Django substr/substring

Python:Hangman TypeError: 'str'对象不支持项目分配

c# - C# 中两种不同类型的列表

python - 如何使用变量作为标识符输入列表中的项目?

python - 将系列的值添加到数据框

java - BigInteger 加法总是 0

python - Gensim doc2vec 在 ngram 上进行训练

python - Django 中迁移的执行顺序