Grouping Python tuple list

前端 未结 7 1607
日久生厌
日久生厌 2020-11-30 07:47

I have a list of (label, count) tuples like this:

[(\'grape\', 100), (\'grape\', 3), (\'apple\', 15), (\'apple\', 10), (\'apple\', 4), (\'banana\', 3)]
         


        
7条回答
  •  暖寄归人
    2020-11-30 08:01

    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).

提交回复
热议问题