molakalapalli ramesh
molakalapalli ramesh

Reputation: 217

Python:List Addition

I have two lists like below.i am getting this from database

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] 

If EmpIDs are same then corresponding values in TotDur should collect and add(sum).

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

How to do this in Python.

Upvotes: 1

Views: 1737

Answers (7)

raton
raton

Reputation: 428

    python 3.2
    res=[]
    for i in set(ID):
         b=[]
         for x,y in enumerate(ID):
              if i==y: b.append(T[x])
    res.append(sum(b))

Upvotes: 0

Abhijit
Abhijit

Reputation: 63737

If the elements are in order as you have shown in your example, you can use itertools.groupby

from itertools import groupby
from operator import itemgetter
[(k , sum(e for _,e in v)) for k,v in groupby(zip(EmpID, TotDur), itemgetter(0))]
[(u'1046', 4.5), (u'8008', 2.7), (u'8011', 1.2)]

infact you don't need to create two separate list and zip it later

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

[(k , sum(e for _,e in v)) for k,v in groupby(Emp_TotDur, itemgetter(0))]

Upvotes: 2

tozlu
tozlu

Reputation: 4865

Try this, it puts sum of all corresponding id's values to a list, later you can access the list with empId and see its sum.

finalList = []
lastEmpId

for index, emp in enumarate(EmdIP):
    if lastEmpId == emp:
        finalList[lastEmpId] += TotDur[index]
    else:
        finalList[lastEmpId] = TotDur[index]
    lastEmpId = emp;

print finalList

Upvotes: 0

Emil Vikström
Emil Vikström

Reputation: 91932

You can zip the two lists, which pairs the elements of the first to the elements of the second into tuples. Then loop over them and use the first part of the tuple as keys in a dictionary:

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]
Result = {}

for (key, value) in zip(EmpID, TotDur):
    if not key in Result:
        Result[key] = value
    else:
        Result[key] += value

# Print the result
for (key, value) in Result.items():
    print key, value

You may want to use an OrderedDict if you want to preserve the order of the Emps

Upvotes: 0

Lucas Hoepner
Lucas Hoepner

Reputation: 1447

You can do it like this

l1 = [1,1,2,3,3]
l2 = [1,2,3,4,5]
last_val=l1[0]
sum=0
list=[]
for pair in zip(l1,l2): 
    if pair[0]!=last_val:
        print(sum)
        list.append(sum)
        sum=0
    last_val=pair[0]
    sum+=pair[1]
list.append(sum)
print(list)

Upvotes: 0

Yuval Adam
Yuval Adam

Reputation: 165242

defaultdict is a good data structure to use, for int fields it assumes the value 0 for new keys, and allows for easy bucket collection:

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

Upvotes: 3

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

you can use defaultdict:

In [60]: from collections import *

In [61]: EmpID = [u'1046', u'1046', u'1046', u'8008', u'8008', u'8011']

In [62]: TotDur = [0.0, 2.0, 2.5, 0.0, 2.7, 1.2]

In [63]: d=defaultdict(int)

In [64]: for x,y in zip(EmpID,TotDur):
    d[x]+=y
   ....:     

In [65]: d
Out[65]: defaultdict(<type 'int'>, {u'8008': 2.7, u'1046': 4.5, u'8011': 1.2})

or simply dict:

In [70]: d=dict()

In [71]: for x,y in zip(EmpID,TotDur):
    d[x]=d.get(x,0)+y
   ....:     

In [72]: d
Out[72]: {u'1046': 4.5, u'8008': 2.7, u'8011': 1.2}

Upvotes: 2

Related Questions