-1

I am new to python, I have a quite simple question. how is it possible to use sum() to do the following code in one line

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

with myList a list of objects that each one contains two attributes a and b

I know we can do the following

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

but how to get the sum of multiplication?

Bashir
  • 2,057
  • 5
  • 19
  • 44
  • so you want the numbers multiplied –  Jul 08 '21 at 09:03
  • Can you post what `myList` contains? – Deneb Jul 08 '21 at 09:03
  • Does this answer your question? [What does "list comprehension" mean? How does it work and how can I use it?](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it) – mkrieger1 Jul 08 '21 at 09:07

1 Answers1

4

You can do:

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

Note the missing [...] brackets, avoiding the spurious constructioon of an in-memory list through a comprehension, and instead passing the generator expression to sum.

You could also throw the kitchen sink of functional utils at this :)

from operator import mul, attrgetter
from itertools import starmap

total = sum(starmap(mul, map(attrgetter("a", "b"), myList)))
user2390182
  • 72,016
  • 6
  • 67
  • 89