Python sum() 函数用法
2023-09-17 22:29:17
sum()
方法返回从给定可迭代对象的左到右开始的整数元素的总数。
语法:
sum(iterable, start)
参数:
返回值:
返回一个整数,指示可迭代对象的所有值的总和。
下面的示例返回可迭代对象的元素总和。
nums = [1, 2, 3, 4, 5]
total = sum(nums)
print("Total = ", total)
total = sum(nums, 5) # start adding 5
print("Total with starting value = ", total)
nums = [10.5, 20.5, 30.5, 4, 5] # with float & int elements
total = sum(nums)
print("Total of mixed elements = ", total)
nums = [3+2j, 5+6j]
total = sum(nums)
print("Total of complex numbers = ", total)
输出:
Total = 15
Total with starting value = 20
Total of mixed elements = 70.5
Total of complex numbers = (8+8j)
sum()
方法还可以接受 set、tuple、dict(仅使用 int 键)来计算所有元素的总和,如下所示。
nums_set = {1, 2, 3, 4, 5}
total = sum(nums_set)
print("Total of set = ", total)
nums_tuple = (1, 2, 3, 4, 5)
total = sum(nums_tuple)
print("Total of tuple = ", total)
nums_dict = {1:'one',2:'two',3:'three'}
total = sum(nums_dict)
print("Total of dict Keys = ", total)
输出:
Total of set = 15
Total of tuple = 15
Total of dict keys = 6
请注意,传递字符串或其他值将导致TypeError
。