在sum函数中,原型是sum(iterable [,start]),它将可迭代对象中的所有内容加上起始值相加.我想知道为什么这里有起始价值?有没有特定的用例需要这个值?
请不要再举例说明如何使用start.我想知道为什么它存在于这个函数中.如果sum函数的原型只是sum(可迭代),并且如果iterable为空则返回None,一切都会正常工作.那么为什么我们需要从这里开始呢?
Mar*_*ers 15
如果要对不是整数的事物求和,则可能需要提供起始值以避免错误.
>>> from datetime import timedelta
>>> timedeltas = [timedelta(1), timedelta(2)]
>>> sum(timedeltas)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'
>>> sum(timedeltas, timedelta())
datetime.timedelta(3)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1816 次 |
| 最近记录: |