Is it possible to access current object while doing list/dict comprehension in Python?

前端 未结 4 1895
慢半拍i
慢半拍i 2020-11-30 14:21

Trying to think of a one-liner to achieve the following ( summing all the values of a key) :

>>> data = [(\'a\',1),(\'b\',3),(\'a\',4),(\'c\',9),(\'         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 15:06

    Use reduce and collections.Counter:

    >>> from operator import add
    >>> from collections import Counter
    >>> reduce(add, (Counter(dict([x])) for x in data))
    Counter({'c': 9, 'a': 5, 'b': 4, 'd': 3})
    

提交回复
热议问题