分组Python元组列表 [英] Grouping Python tuple list
本文介绍了分组Python元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的(标签,计数)元组列表:
I have a list of (label, count) tuples like this:
[('grape', 100), ('grape', 3), ('apple', 15), ('apple', 10), ('apple', 4), ('banana', 3)]
由此,我想对所有具有相同标签的值求和(相同的标签始终相邻),并以相同的标签顺序返回列表:
From that I want to sum all values with the same label (same labels always adjacent) and return a list in the same label order:
[('grape', 103), ('apple', 29), ('banana', 3)]
我知道我可以用类似的方法解决它:
I know I could solve it with something like:
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/优雅/有效的方式来做到这一点?
But is there a more Pythonic / elegant / efficient way to do this?
推荐答案
itertools.groupby
可以做您想做的事情:
itertools.groupby
can do what you want:
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)]
>>>
这篇关于分组Python元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文