本系列将会陆续整理分享一些的Python内置函数。
-
通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj
提取码:mnsj
-
前往GitHub获取:
https://github.com/returu/Python_built-in_functions
sum(iterable, /, start=0)
-
iterable:可迭代对象,如列表、元组、集合等,其中的元素必须是数字(整数或浮点数); -
start:可选参数,求和的起始值,默认为0,不能是字符串。
返回值:
下面是一些使用 sum() 函数的示例:
-
示例 1:基本使用
# 求列表中所有元素的总和
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total) # 输出 15
# 求元组中所有元素的总和
numbers_tuple = (1.5, 2.5, 3.5)
total_tuple = sum(numbers_tuple)
print(total_tuple)
# 输出 7.5
-
示例 2:使用初始值
# 使用初始值
numbers_with_start = [1, 2, 3, 4, 5]
total_with_start = sum(numbers_with_start, 10)
print(total_with_start)
# 输出 25
# start 值不允许为字符串
try:
sum(numbers_with_start, '10')
except TypeError as e:
print(e)
# 输出 TypeError: sum() can't sum strings [use ''.join(seq) instead]
-
示例 3:计算布尔值列表中 True 的数量
# 包含布尔值的列表
bool_list = [True, False, True, True, False]
# 计算列表中 True 的数量
true_count = sum(bool_list)
print(true_count) # 输出 3


本篇文章来源于微信公众号: 码农设计师