简体   繁体   English

如何在python中的对象列表中求和元素

[英]How to SUM elements within a list of objects in python

I am trying to sum (plus other maths operations) a specific attribute of my list of objects and I do not know how to do it.我正在尝试对我的对象列表的特定属性求和(加上其他数学运算),但我不知道该怎么做。

A example of what I am trying to do is:我正在尝试做的一个例子是:

my_list = [
             {
               'brand': 'Totoya',
               'quantity': 10
             },
             {
               'brand': 'Honda',
               'quantity': 20
             },
             {
               'brand': 'Hyundai',
               'quantity': 30
             }
           ]

I want to SUM all the 'quantity'.我想总结所有的“数量”。 Is it possible without a loop?没有循环可以吗? using collections?使用集合? Counter?柜台?

Output = 60

as the input is:因为输入是:

my_list = [
             {
               'brand': 'Totoya',
               'quantity': 10
             },
             {
               'brand': 'Honda',
               'quantity': 20
             },
             {
               'brand': 'Hyundai',
               'quantity': 30
             }
           ]

You can loop over it as this:你可以像这样循环它:

counter = 0
for i in my_list:
    counter += i['quantity']
print(counter)

or in oneliner:或在单线:

print(sum(i['quantity'] for i in my_list))

Python contains good functions for functional programming. Python 包含用于函数式编程的好函数。

my_list = ...

# Select the quantities from my_list
quantities = map(lambda x: x['quantity'], my_list) 
# Computes the sum of quantities
total = sum(quantities)

Another alternative way to do this执行此操作的另一种替代方法

from operator import itemgetter

getter = itemgetter('quantity')
sum(map(getter, my_list))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM