Python中sum
函数用于对可迭代对象中的元素进行求和,其基本用法如下:
一、基本语法
sum(iterable[, start])
-
iterable :必须参数,支持列表、元组、集合、字典(仅对字典的键求和)等可迭代对象。
-
start :可选参数,指定初始值(默认为0),用于在总和基础上累加。
二、核心用法示例
-
基础求和
numbers = [1, 2, 3, 4, 5] total = sum(numbers) # 输出 15
-
指定起始值
total = sum(numbers, 10) # 输出 25(15 + 10)
-
处理复数
complex_numbers = [1+2j, 3+4j] total = sum(complex_numbers) # 输出 (4+6j)
-
合并多个列表
lists = [[1, 2], [3, 4], [5, 6]] total = sum(lists, []) # 输出 21
注意:合并列表时推荐使用
extend
方法,sum
会创建新列表,效率较低。
三、扩展应用
-
字典键求和
scores = {'Alice': 85, 'Bob': 90, 'Charlie': 78} total = sum(scores.values()) # 输出 253
-
处理非数字类型
sum
仅支持支持加法运算的对象(如数字、复数),否则会报错。
四、性能优化
对于大规模数据集,建议使用numpy
库的np.sum
函数,其计算速度更快。
总结 :sum
函数简洁高效,适用于多种数据类型和场景,使用时需注意参数类型和数据结构选择。