我有一个这样的(标签,计数)元组列表:
[('grape', 100), ('grape', 3), ('apple', 15), ('apple', 10), ('apple', 4), ('banana', 3)]
由此,我想对所有具有相同标签的值求和(相同的标签始终相邻),并以相同的标签顺序返回列表:
[('grape', 103), ('apple', 29), ('banana', 3)]
我知道我可以用以下方法解决它:
def group(l): result = [] if l: this_label = l[0][0] this_count = 0 for label, count in l: if label != this_label: result.append((this_label, this_count)) this_label = label this_count = 0 this_count += count result.append((this_label, this_count)) return result
但是,有没有更Pythonic /优雅/有效的方法来做到这一点?
itertools.groupby 可以做你想做的:
itertools.groupby
import itertools import operator L = [('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)] >>>