Python one-liner

Question:

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 the total value. I want it in a one-liner. How can I do it?

Asked By: Nazmul Hasan

||

Answers:

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)
Answered By: Amber

There isn’t any need to double up on the sum() calls:

total = sum(v.amount for ob in self.oblist for v in ob.anotherob)
Answered By: John La Rooy
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.