Grouping Python tuple list

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

    >>> from itertools import groupby
    >>> from operator import itemgetter
    >>> L=[('grape', 100), ('grape', 3), ('apple', 15), ('apple', 10), ('apple', 4), ('banana', 3)]
    >>> [(x,sum(map(itemgetter(1),y))) for x,y in groupby(L, itemgetter(0))]
    [('grape', 103), ('apple', 29), ('banana', 3)]
    

提交回复
热议问题