为了账号安全,请及时绑定邮箱和手机立即绑定

python的sum函数怎么用 ?

python的sum函数怎么用 ?

长风秋雁 2019-02-26 11:07:25
python的sum函数怎么用 
查看完整描述

4 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

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

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

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

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

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

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

比如:


查看完整回答
反对 回复 2019-03-27
?
慕少森

TA贡献2019条经验 获得超9个赞

按照惯例,在开发语言中,sum函数是求和函数,求多个数据的和

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

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

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

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




查看完整回答
反对 回复 2019-03-27
?
慕婉清6462132

TA贡献1804条经验 获得超2个赞

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.


查看完整回答
反对 回复 2019-03-27
?
米脂

TA贡献1836条经验 获得超3个赞

sum是python中一个很实用的函数,但是要注意它的使用,我第一次用的时候,就把它这样用了:

s = sum(1,2,3)

结果就悲剧啦

其实sum()的参数是一个list

例如:

sum([1,2,3])

sum(range(1,11))

还有一个比较有意思的用法

a = range(1,11)

b = range(1,10)

c =  sum([item for item in a if item in b])

print c

输出:

45

1


查看完整回答
反对 回复 2019-03-27
  • 4 回答
  • 0 关注
  • 853 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信