1

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.

7 Answers 7

3

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})
Sign up to request clarification or add additional context in comments.

3 Comments

How's this different from my answer?
It isn't, I didn't notice yours until I posted mine ;)
@AshwiniChaudhary: Why does it need to be different? It does explain the int behaviour explicitly, which I found useful.
2

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

Comments

2

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}

Comments

0

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)

Comments

0

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

Comments

0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.