如何汇总列表元素

时间:2012-11-29 05:58:58

标签: python zip sum

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

从上面的功能,我得到如下结果。此处1046,8008,8011EmpID1.0,2.3等为值。

[(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

3 个答案:

答案 0 :(得分: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)))

答案 1 :(得分:0)

使用当前EmpID和该EmpID的日期值总和保留一个变量。当EmpID更改时,输出它(或将其保存到列表,intead)

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

答案 2 :(得分: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])]