python 12.5 -- python 序列中的求和函数sum()详解

python 中,序列表示索引为非负整数的有序对象集合,包括字符串,列表和元组。

求和函数sum()

sum的函数原型为

sum(s[,start])

其中

  • iterable 是可迭代对象,如:列表(list)、元组(tuple)、集合(set)、字典(dictionary)。

  • start 是指定相加的参数,如果没有设置这个值,默认为0

所以说:

>>> sum(1,2,3) # is incorrect
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum expected at most 2 arguments, got 3
>>> sum((1,2,3)) # is correct
6
>>> # the reason is:the expression above equals to this
... tuple = (1,2,3)
>>> sum(tuple)
6
>>> # you also can use this function on
... # list
... sum([1,2,3])
6
>>> # dict (sum of keys, not values)
... sum({1:'a',2:'b'})
3
>>> # range
... sum(range(1,4))
6
发布了64 篇原创文章 · 获赞 6 · 访问量 5565

猜你喜欢

转载自blog.csdn.net/weixin_45494811/article/details/104077527
今日推荐