将第一列上的项目分组到字典中;adefaultdict
使这更容易一些:
from collections import defaultdict
sums = defaultdict(int)
for tup in l:
sums[tup[0]] += int(tup[1])
defaultdict
如果键不存在,只需调用传入的工厂生成默认值(int
在这种情况下,生成 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})
然后打印总和很简单:
for key in sorted(sums):
print 'sum{}={}'.format(key, sums[key])
如果您的输入列表已排序,请使用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
您可以直接切换到打印:
for key, group in groupby(l, key=itemgetter(0)):
print 'sum{}={}'.format(key, sum(t[1]) for t in group))
如果没有外部模块,我只会去找字典;这将比上述任何一个选项都慢:
sums = {}
for tup in l:
sums[tup[0]] = sums.get(tup[0], 0) + int(tup[1])
或者,对于排序的变体:
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)