Python sum()函数
描述
sum()函数返回任何可迭代对象(列表或元组)中所有数字项的总和。默认情况下,可选的start参数为0。如果给定了start值,则列表中的数字将添加到start值。
语法
sum(iterable, start)
参数
x : an iterable with numeric operands
start: initial value of sum
返回值
该函数返回可迭代对象中数值操作数的和
示例
x = [10,20,30]
total = sum(x)
print ("x: ",x, "sum(x): ", total)
x = (10, -20, 10)
total = sum(x)
print ("x: ",x, "sum(x): ", total)
x = [10,20,30]
start = 5
total = sum(x, start)
print ("x: ",x, "start:", start, "sum(x, start): ", total)
这将产生以下输出:
x: [10, 20, 30] sum(x): 60
x: (10, -20, 10) sum(x): 0
x: [10, 20, 30] start: 5 sum(x, start): 65