itertools.groupby可以做你想做的:
import itertoolsimport operatorL = [('grape', 100), ('grape', 3), ('apple', 15), ('apple', 10), ('apple', 4), ('banana', 3)]def accumulate(l): it = itertools.groupby(l, operator.itemgetter(0)) for key, subiter in it: yield key, sum(item[1] for item in subiter)>>> print list(accumulate(L))[('grape', 103), ('apple', 29), ('banana', 3)]>>>
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)