Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python one-liner

Tags:

python

sum

I want a one-liner solution In Python of the following code but how?

total = 0
for ob in self.oblist:
    total+=sum(v.amount for v in ob.anoutherob)

It returns total value. I want it one liner , plz any one help me

like image 993
Nazmul Hasan Avatar asked Aug 18 '10 03:08

Nazmul Hasan


2 Answers

No need to double up on the sum() calls

total = sum(v.amount for ob in self.oblist for v in ob.anotherob)
like image 140
John La Rooy Avatar answered Sep 19 '22 09:09

John La Rooy


You can just collapse the for loop into another level of comprehension:

total = sum(sum(v.amount for v in ob.anotherob) for ob in self.oblist)
like image 22
Amber Avatar answered Sep 20 '22 09:09

Amber