2 回答
TA贡献2065条经验 获得超14个赞
将第一列上的项目分组到字典中;一个defaultdict使它容易一些:
from collections import defaultdict
sums = defaultdict(int)
for tup in l:
sums[tup[0]] += int(tup[1])
defaultdict如果不存在键,只需调用传入的工厂以产生默认值(int在这种情况下,产生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)
TA贡献1795条经验 获得超7个赞
>>> from collections import defaultdict
>>> a = [["a",1,2],["a",2,3],["b",45,2]]
>>> my_dict = defaultdict(list)
>>> for itm in a:
... my_dict[itm[0]].append(itm)
...
>>> for k,v in my_dict.items():
... print "Sum %s:%s"%(k,sum(zip(*v)[1]))
...
Sum a:3
Sum b:45
添加回答
举报