Python 内建函数 - sum(iterable[, start])

本文介绍了Python的内建函数sum(),它用于从左到右累加序列的元素,可选地加上start值,默认为0。注意start值不能是字符串。文章提到了在特定场景下,可以使用'.join(sequence)'拼接字符串,math.fsum()进行高精度浮点数相加,以及itertools.chain()链接多个迭代器的替代方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Manual

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and the start value is not allowed to be a string.

For some use cases, there are good alternatives to sum(). The preferred, fast way to concatenate a sequence of strings is by calling ”.join(sequence). To add floating point values with extended precision, see math.fsum(). To concatenate a series of iterables, consider using itertools.chain().

直译

计算startiterable从左到右的项合计。
start默认为0,其值不允许字符串;iterable的项通常是数字。
对于一些其他使用情形,这有一些更好的替代sum()的选择。首选,可以通过调用”.join(sequence)快速链接字符串序列;用扩展精度运算math.fsum()求浮点值的和;链接一系列迭代,建议使用itertools.chain()

实例

>>> a = [i for i in range(1,101)]
>>> sum(a)
5050
>>> sum(a, 505)
5555

拓展阅读

math.fsum()
itertools.chain()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值