亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 961 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號