Grouping Python tuple list

2020-01-27 05:09发布

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

But is there a more Pythonic / elegant / efficient way to do this?

7条回答
倾城 Initia
2楼-- · 2020-01-27 06:15

using itertools and list comprehensions

import itertools

[(key, sum(num for _, num in value))
    for key, value in itertools.groupby(l, lambda x: x[0])]

Edit: as gnibbler pointed out: if l isn't already sorted replace it with sorted(l).

查看更多
登录 后发表回答