我的列表(标签,计数)元组是这样的:分组Python的元组列表
[('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
但有一个MO重新Pythonic /优雅/有效的方式来做到这一点?
我喜欢用'operator.itemgetter'来代替'lambda'。 – jathanism 2010-02-12 01:48:37
这要求列表按第一个键排序。如果它尚未排序,那么ghostdog74的defaultdict方法是更好的解决方案。 – 2016-10-10 21:05:35