Python - sum values in dictionary

后端 未结 3 865
逝去的感伤
逝去的感伤 2020-11-29 20:40

I have got pretty simple list:

example_list = [
    {\'points\': 400, \'gold\': 2480},
    {\'points\': 100, \'gold\': 610},
    {\'points\': 100, \'gold\':          


        
相关标签:
3条回答
  • 2020-11-29 20:45

    If you're memory conscious:

    sum(item['gold'] for item in example_list)
    

    If you're extremely time conscious:

    sum([item['gold'] for item in example_list])
    

    In most cases just use the generator expression, as the performance increase is only noticeable on a very large dataset/very hot code path.

    See this answer for an explanation of why you should avoid using map.

    See this answer for some real-world timing comparisons of list comprehension vs generator expressions.

    0 讨论(0)
  • 2020-11-29 20:57

    If you prefer map, this works too:

     import operator
     total_gold = sum(map(operator.itemgetter('gold'),example_list))
    

    But I think the generator posted by g.d.d.c is significantly better. This answer is really just to point out the existence of operator.itemgetter.

    0 讨论(0)
  • 2020-11-29 21:07
    sum(item['gold'] for item in myList)
    
    0 讨论(0)
提交回复
热议问题