总结列在清单列表中的每个元素 [英] Sum column in list in list for each element

查看:187
本文介绍了总结列在清单列表中的每个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关列表的列表,是否有求和为每个特定元件的列在列表中(使用python)的一些方法。一个例子...

For a list of lists, is there some way of summing a column for each specific element in the list (using python). An example...

l=[['A1','1','2'],['A1','1','2'],['A1','3','3'],['B1','1','2'],['B1','5','5'],[...]]

现在总结为A1的在第一列仅,B1的等,并获得所需的输出...

Now sum the first column only for A1's, B1's etc and get the desired output as...

sumA1=5
sumB1=6
sumC1.......

现在列表值可能会改变,所以我不想提到A1,B1 ......。它可能会成为A3,B4 ....所以最好的办法是根据指数[0](列的数量/类型不会改变)来总结。 在code我有个大气压只是一个简单的列表COM prehension,总结各1列,无论是否A1,B1等。

Now list values may change so I don't want reference to "A1, B1..". It may become A3, B4....so the best way would be to sum according to index[0] (the number/ type of columns wont change). The code I have atm is just a simple list comprehension that sums all of column 1 regardless of whether A1, B1, etc..

for i in l:
    total = sum(float(i[1]) for i in l if i[1])

考虑总会有相同的项目数为每一个A1,B1。让我们说10,另一种是将总结每10个号码中我[1]但我需要能够说'的第一10个号码是A1的总和,该第二10个数字的总和为B2,等等。鸭preciate帮助

Considering there will always be the same number of items for each "A1, B1.." let's say 10, an alternative would be to sum every 10 numbers in i[1] but then I'd need to be able to say 'the sum of the 1st 10 numbers are for A1, the sum of the 2nd 10 numbers is B2, etc'. Appreciate the help

推荐答案

小组第一列到字典中的物品;一个 defaultdict ,使这变得更轻松:

Group the items on the first column into a dictionary; a defaultdict makes that a little easier:

from collections import defaultdict

sums = defaultdict(int)

for tup in l:
    sums[tup[0]] += int(tup[1])

defaultdict 只是调用传入的工厂生产的默认值,如果key不是present(<$ C C $> INT 在这种情况下,产生了 0 ):

defaultdict simply calls the passed-in factory to produce a default value if a key isn't present (int in this case, producing a 0):

>>> d = defaultdict(int)
>>> d['foo']
0

演示:

>>> l=[['A1','1','2'],['A1','1','2'],['A1','3','3'],['B1','1','2'],['B1','5','5']]
>>> from collections import defaultdict
>>> sums = defaultdict(int)
>>> for tup in l:
...     sums[tup[0]] += int(tup[1])
... 
>>> sums
defaultdict(<class 'int'>, {'B1': 6, 'A1': 5})

然后打印的金额就是这么简单:

Then printing the sums is as simple as:

for key in sorted(sums):
    print 'sum{}={}'.format(key, sums[key])

如果您的输入列表中的排序的,使用 itertools.groupby()

If your input list is sorted, use itertools.groupby():

from itertools import groupby
from operator import itemgetter

sums = {key: sum(int(t[1]) for t in group) for key, group in groupby(l, key=itemgetter(0))}

演示:

>>> from itertools import groupby
>>> from operator import itemgetter
>>> {key: sum(int(t[1]) for t in group) for key, group in groupby(l, key=itemgetter(0))}
{'B1': 6, 'A1': 5}

事实上,与排序列表和 GROUPBY 则可以切换直接打印:

In fact, with a sorted list and groupby you can switch straight to printing:

for key, group in groupby(l, key=itemgetter(0)):
    print 'sum{}={}'.format(key, sum(t[1]) for t in group))

无需外接模块,我只是去一个字典;这是怎么回事比任何上述选项要慢一些:

Without external modules I'd just go for a dictionary; this is going to be slower than either of the above options:

sums = {}

for tup in l:
    sums[tup[0]] = sums.get(tup[0], 0) + int(tup[1])

或者,可将储存的变体:

or, for the sorted variant:

sum, last = 0, l[0][0]
for tup in l:
    key = tup[0]
    if last != key and sum:
        print 'sum{}={}'.format(last, sum)
        sum, last = 0, key
    sum += int(tup[1])
if sum:
    print 'sum{}={}'.format(key, sum)

这篇关于总结列在清单列表中的每个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆