简体   繁体   English

如何在Python中向后添加?

[英]How to add backwards in Python?

我有一个数字,例如35。是否有做35+34+33.....+1 = 630的函数,我知道有累加,但更多用于数组而不是实数。

借助数学的力量,您可以高效地进行计算:

result = 35 * (35 + 1) // 2  # 630

There is not quite a built-in function that does exactly that, but you can combine the sum function with a range object. 没有一个完全可以执行此操作的内置函数,但是您可以将sum函数与一个range对象结合使用。

result = sum(range(35, 0, -1))

The -1 in that expression makes the range count backwards, so the sum starts with 35 , it continues until it reaches 0 then stops (not including the 0 in the sum, though that does not matter here). 该表达式中的-1使范围向后计数,因此sum35开始,一直持续到达到0然后停止(不包括总和中的0 ,尽管在这里无关紧要)。 Of course, the addition operator is associative and commutative, so the order does not matter theoretically. 当然,加法运算符是关联和可交换的,因此顺序在理论上无关紧要。 But this does what you asked, in the order you asked. 但这会按照您的要求执行您的要求。 There are, of course, also other ways to get the same result. 当然,还有其他方法可以获得相同的结果。

In a comment, you seem to say that you want to use the variable maxlen rather than the constant 35 . 在注释中,您似乎似乎要使用变量maxlen而不是常数35 Then just use 然后使用

result = sum(range(maxlen, 0, -1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM