python的sum函数怎么用

Python013

python的sum函数怎么用,第1张

sum(iterable[, start]) ,iterable为可迭代对象,如:

sum([ ], start)  , #iterable为list列表。

sum(( ), start ) , #iterable为tuple元组。

最后的值=可迭代对应里面的数相加的值 + start的值

start默认为0,如果不写就是0,为0时可以不写,即sum()的参数最多为两个,其中第一个必须为iterable。

按照惯例,在开发语言中,sum函数是求和函数,求多个数据的和,而在python中,虽然也是求和函数,但稍微有些差别,sum()传入的参数得是可迭代对象(比如列表就是一个可迭代对象),返回这个被传入可迭代对象内参数的和。

比如:

在开发语言中,sum函数是求和函数,用于求多个数据的和。而在python中,虽然也是求和函数,但稍微有些差别,sum()传入的参数得是可迭代对象(比如列表就是一个可迭代对象),返回这个被传入可迭代对象内参数的和。

相关推荐:《Python入门教程》

比如:

还可以给一个初始值,比如:

这样得到的结果就是在20基础之上再加上可迭代对象内参数的和。

补充一句,sum函数既然只能传入可迭代对象,那么整形数据是不行的,会报错,比如:

sum(iterable[, start]) ,iterable为可迭代对象,如:

sum([ ], start) #iterable为list列表

sum(( ), start )#iterable为tuple元组

......

最后的值 = 可迭代对象里面的数相加的值 + start的值

start默认为0,如果不写就是0,为0时可以不写

即sum()的参数最多为两个,其中第一个必须为iterable,例如:

>>>sum([1, 2, 3,], 4)

10

>>>sum((1, 2), 3)

6

如果你写成sum([1,2,3]),start就是默认值 0

>>>sum([1, 2, 3])

6

>>>sum([ ], 2)

2

>>>sum(( ), )

0

>>>sum([1, 2] , 0)

3

当然iterable为dictionary字典时也是可以的:

>>>sum({1: 'b', 7: 'a'})

8

>>>sum({1:'b', 7:'a'}, 9)

17

下面这些写法目前是不被接受的(以list为例,其他iterable同理):

一、

>>>sum([1,2],[3,4])

Traceback (most recent call last):

File "<pyshell#115>", line 1, in <module>

sum([1,2],[3,4])

TypeError: can only concatenate list (not "int") to list

二、

>>>sum(4,[1,2,3])

Traceback (most recent call last):

File "<pyshell#116>", line 1, in <module>

sum(4,[1,2,3])

TypeError: 'int' object is not iterable

三、

>>>sum()

Traceback (most recent call last):

File "<pyshell#117>", line 1, in <module>

sum()

TypeError: sum expected at least 1 arguments, got 0

四、

>>>sum(,2)

SyntaxError: invalid syntax

五、

>>>sum(1,3)

Traceback (most recent call last):

File "<pyshell#112>", line 1, in <module>

sum(1,3)

TypeError: 'int' object is not iterable

附其官方解释:

>>>help(sum)

Help on built-in function sum in module builtins:

sum(...)

sum(iterable[, start]) ->value

Return the sum of an iterable of numbers (NOT strings) plus the value

of parameter 'start' (which defaults to 0). When the iterable is

empty, return start.