簡體   English   中英

對象列表中的乘法和

[英]sum of multiplication in a list of objects

我是python的新手,我有一個非常簡單的問題。 如何使用sum()在一行中執行以下代碼

total= 0.0
for record in myList:
    a= record.a
    b= record.b
   total+= (a*b)

使用myList一個對象列表,每個對象都包含兩個屬性ab

我知道我們可以做到以下幾點

sum([3,4,5]) == 3 + 4 + 5 == 12

但是如何得到乘法的總和呢?

你可以做:

total = sum(rec.a * rec.b for rec in myList)

注意缺少的[...]括號,通過推導避免了內存列表的虛假構造,而是將生成器表達式傳遞給sum

你也可以把功能性工具的廚房水槽扔到這里:)

from operator import mul, attrgetter
from itertools import starmap

total = sum(starmap(mul, map(attrgetter("a", "b"), myList)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM