我有一个这样的(标签,计数)元组列表:
[('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/优雅/高效的方法来做到这一点?
原文由 hoju 发布,翻译遵循 CC BY-SA 4.0 许可协议
itertools.groupby
可以做你想做的事: