當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python sum()用法及代碼示例


列表中的數字總和在任何地方都是必需的。 Python提供了一個內置函數sum(),用於對列表中的數字求和。

用法:

sum(iterable, start)  
iterable: iterable can be anything list , tuples or dictionaries ,
 but most importantly it should be numbers.
start :this start is added to the sum of 
numbers in the iterable. 
If start is not given in the syntax , it is assumed to be 0.

可能的兩種語法:

sum(a)
a is the list , it adds up all the numbers in the 
list a and takes start to be 0, so returning 
only the sum of the numbers in the list.
sum(a, start)
this returns the sum of the list + start 

以下是sum()的Python實現


# Python code to demonstrate the working of  
# sum() 
   
numbers = [1,2,3,4,5,1,4,5] 
  
# start parameter is not provided 
Sum = sum(numbers) 
print(Sum) 
  
# start = 10 
Sum = sum(numbers, 10) 
print(Sum)

輸出:

25
35

Error and Exceptions

TypeError:如果列表中沒有數字,則會引發此錯誤。

# Python code to demonstrate the exception of  
# sum() 
arr = ["a"] 
  
# start parameter is not provided 
Sum = sum(arr) 
print(Sum) 
  
# start = 10 
Sum = sum(arr, 10) 
print(Sum)

運行時錯誤:

Traceback (most recent call last):
  File "/home/23f0f6c9e022aa96d6c560a7eb4cf387.py", line 6, in 
    Sum = sum(arr)
TypeError:unsupported operand type(s) for +:'int' and 'str'

因此列表應包含數字

實際應用:需要計算總和以進行進一步運算(例如找出數字的平均值)的問題。

# Python code to demonstrate the practical application 
# of sum() 
  
numbers = [1,2,3,4,5,1,4,5] 
  
# start = 10 
Sum = sum(numbers) 
average= Sum/len(numbers)  
print average

輸出:

3


相關用法


注:本文由純淨天空篩選整理自Striver大神的英文原創作品 sum() function in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。