我的列表(標籤,計數)元組是這樣的:分組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