Skip to main content
 首页 » 编程设计

Python:列表加法

2025年05月04日13oomusou

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

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})