python中sum函数的用法
时间: 2023-07-14 12:00:26 浏览: 49
在Python中,`sum()`函数用于计算可迭代(如列表、元组、集合等)中所有元素的总和。它接受一个可迭代对象作为参数,并返回总和结果。
以下`sum()`函数的一些常见用法例:
1. 对列表进行求和:
```
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total) # 输出:15
```
2. 对元组进行求和:
```python
numbers = (1, 2, 3, 4, 5)
total = sum(numbers)
print(total) # 输出:15
```
3. 对集合进行求和:
```python
numbers = {1, 2, 3, 4, 5}
total = sum(numbers)
print(total) # 输出:15
```
4. 对带有自定义对象的可迭代对象进行求和,需要提供一个可选的`key`参数来指定如何提取每个对象的值进行求和。例如,对包含学生对象的列表按照他们的分数求和:
```python
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
students = [Student('Alice', 80), Student('Bob', 90), Student('Charlie', 70)]
total_score = sum(students, key=lambda x: x.score)
print(total_score) # 输出:240
```
总结一下,`sum()`函数用于计算可迭代对象中元素的总和,并且可以通过`key`参数进行自定义求和的方式。