Ich habe eine Liste von (Label, count) Tupel wie folgt aus:Gruppierung Python Tupel Liste
[('grape', 100), ('grape', 3), ('apple', 15), ('apple', 10), ('apple', 4), ('banana', 3)]
Von dass ich will alle Werte mit dem gleichen Etikett (gleiche Etiketten immer benachbart) und gibt eine Liste zusammenzufassen in der gleichen Label Reihenfolge:
[('grape', 103), ('apple', 29), ('banana', 3)]
ich weiß, ich es mit so etwas wie lösen könnte:
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
Aber gibt es einen mo re Pythonic/eleganter/effizienter Weg dies zu tun?
Ich mag die Verwendung von 'operator.itemgetter' anstelle von' Lambda'. – jathanism
Dazu muss die Liste nach dem ersten Schlüssel sortiert werden. Wenn es nicht bereits sortiert ist, ist der Defaultdict-Ansatz von ghostdog74 eine viel bessere Lösung. –