如何解决分组Python元组列表
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)]
>>>
解决方法
我有一个这样的(标签,计数)元组列表:
[('grape',100),('grape',3),('apple',15),10),4),('banana',3)]
由此,我想对所有具有相同标签的值求和(相同的标签始终相邻),并以相同的标签顺序返回列表:
[('grape',103),29),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 /优雅/有效的方法来做到这一点?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。