下面是Python中sum函数的功能详解:
1. sum函数的功能和作用
Python中的sum函数用于计算可迭代对象中所有元素的总和,返回一个数值。该函数的语法为:
sum(iterable[, start])
其中,iterable是可迭代对象,可以是列表、元组、集合或其他可迭代类型;start是可选参数,如果指定,则会把它加到所有元素的总和中。
sum函数只接受数值类型的参数,否则会抛出异常TypeError。
2. sum函数的使用方法
例如,我们有一个列表list1,需要计算所有元素的总和,可以使用sum函数:
list1 = [1, 2, 3, 4, 5]
total = sum(list1)
print(total) # 输出15
此时,sum函数会把1+2+3+4+5,得出结果15,并赋值给变量total。
另外,我们还可以通过start参数设置起始值,比如:
list2 = [1, 2, 3, 4, 5]
total = sum(list2, 10)
print(total) # 输出25
此时,sum函数会把1+2+3+4+5+10,得出结果25,并赋值给变量total。
3. 实用案例
求平均数
sum函数常常和len函数一起使用,用来求列表的平均数。
list3 = [1, 2, 3, 4, 5]
average = sum(list3) / len(list3)
print(average) # 输出3.0
求商品总金额
如果我们有一些商品,需要计算它们的总金额,可以使用sum函数操作其价格列表。
prices = [10.5, 20.3, 5.2, 7.8, 15.6]
total_price = sum(prices)
print(total_price) # 输出59.4
以上就是Python中sum函数的功能详解和使用方法,希望对你有所帮助。