开发者

Python one-liner

开发者 https://www.devze.com 2023-01-12 04:49 出处:网络
I want a one-liner solution in Python of the following code, but how? total = 开发者_如何学编程0

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?


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)


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消