列表中的数字总和在任何地方都是必需的。Python提供了一个内置函数sum(),用于汇总列表中的数字。 语法:
null
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
错误和例外
类型错误: 如果列表中有其他数字,则会出现此错误。
# 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
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END