0
list_pairs = str(zip(GetEmpID[row],Duration[row]))

从上面的函数,我得到如下结果。这1046,8008,8011EmpID's 和1.0,2.3etc 是值。

[(u'1046', 1.0)]
[(u'8008', 2.3)]
[(u'8008', 2.2)]
[(u'8011', 1.3)]

我的结果应该如下所示。如果 EmpID 相同,则添加(总和)该元素。如何在 Python 中执行此操作。

[(u'1046', 1.0)]
   total = 1.0    

[(u'8008', 2.3)]
[(u'8008', 2.2)] 
   total = 4.5

[(u'8011', 1.3)]
   total = 1.3
4

3 回答 3

3
answer = []
for empId, entries in itertools.groupby(sorted(list_pairs, key=operator.itemgetter(0)), key=operator.itemgetter(0)):
    answer.append((empId, sum(entry[1] for entry in entries)))


In [17]: list_pairs = [(u'1046', 1.0), (u'8008', 2.3), (u'8008', 2.2), (u'8011', 1.3)]

In [18]: answer = []

In [19]: for empId, entries in itertools.groupby(sorted(list_pairs, key=operator.itemgetter(0)), key=operator.itemgetter(0)):
   ....:     answer.append((empId, sum(entry[1] for entry in entries)))
   ....:     

In [20]: answer
Out[20]: [(u'1046', 1.0), (u'8008', 4.5), (u'8011', 1.3)]

为了使这个可读

answer = []
list_pairs.sort(key=operator.itemgetter(0))
groups = itertools.groupby(list_pairs, key=operator.itemgetter(0))
for empId, entries in groups:
    answer.append((empId, sum(entry[1] for entry in entries)))
于 2012-11-29T06:02:11.113 回答
0

保留一个具有当前 EmpID 的变量以及该 EmpID 迄今为止的值总和。当 EmpID 更改时,将其输出(或将其保存到列表中)

list_pairs = str(zip(GetEmpID[row],Duration[row]))
last=""
last_sum=0
for empid, value in list_pairs:
    if empid!=last:
        if last:
            print last, last_sum
        last, last_sum= empid, 0
    else:
        last_sum+=value
print last, last_sum
于 2012-11-29T06:05:06.450 回答
0

如果您需要通过在一行中执行来输出,试试这个。

data=[(u'1046', 1.0), (u'8008', 2.2999999999999998), (u'8008', 2.2000000000000002), (u'8011', 1.3)]
import itertools
[(key, sum(x for _,x in value))for key, value in itertools.groupby(data, lambda x: x[0])]
于 2012-11-29T11:07:58.337 回答