简体   繁体   English

如何汇总列表元素

[英]how to sum list elements

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

From the above function, I am getting result like below. 从上面的函数,我得到如下结果。 Here 1046,8008,8011 are EmpID 's and 1.0,2.3 etc are values. 这里1046,8008,8011EmpID ,而1.0,2.3等是值。

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

My result should be like below.If EmpID same then add(sum) that elements.How to do this in Python. 我的结果应该如下所示。如果EmpID相同,则添加(sum)该元素。如何在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
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)]

To make this readable : 为了使其可读

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

Keep a variable with the current EmpID and the sum of values to date for that EmpID. 保留一个具有当前EmpID的变量以及该EmpID的最新值的总和。 When EmpID changes, output it (or save it to a list, intead) 当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

If you need output by executing in a single line, try this. 如果需要通过单行执行输出,请尝试此操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM