蟒蛇单行

时间:2010-08-18 03:33:21

标签: python sum

我想要一个单行解决方案在Python中使用以下代码,但是如何?

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

它返回总值。我想要一个班轮,PLZ任何一个帮助我

2 个答案:

答案 0 :(得分:30)

无需加倍sum()来电

total = sum(v.amount for ob in self.oblist for v in ob.anotherob)

答案 1 :(得分:7)

您可以将for循环折叠到另一个理解级别:

total = sum(sum(v.amount for v in ob.anotherob) for ob in self.oblist)