Grouping Python tuple list

前端 未结 7 1604
日久生厌
日久生厌 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:25

    itertools.groupby can do what you want:

    import itertools
    import operator
    
    L = [('grape', 100), ('grape', 3), ('apple', 15), ('apple', 10),
         ('apple', 4), ('banana', 3)]
    
    def accumulate(l):
        it = itertools.groupby(l, operator.itemgetter(0))
        for key, subiter in it:
           yield key, sum(item[1] for item in subiter) 
    
    >>> print list(accumulate(L))
    [('grape', 103), ('apple', 29), ('banana', 3)]
    >>> 
    
    0 讨论(0)
提交回复
热议问题