1. 使用内置函数 `sum()` 和 `len()`:
```python
def mean_list(numbers):
return sum(numbers) / len(numbers)
my_list = [1, 2, 3, 4, 5]
print(mean_list(my_list)) 输出:3.0
2. 使用 `for` 循环遍历列表:
```python
def mean_list_loop(numbers):
total = 0
for n in numbers:
total += n
return total / len(numbers)
my_list = [1, 2, 3, 4, 5]
print(mean_list_loop(my_list)) 输出:3.0
3. 使用 `numpy` 库的 `mean()` 函数:
```python
import numpy as np
def mean_list_numpy(numbers):
return np.mean(numbers)
my_list = [1, 2, 3, 4, 5]
print(mean_list_numpy(my_list)) 输出:3.0
4. 使用 `pandas` 库的 `mean()` 函数(如果列表是 `pandas` 数据框的一列):
```python
import pandas as pd
def mean_list_pandas(series):
return series.mean()
my_series = pd.Series([1, 2, 3, 4, 5])
print(mean_list_pandas(my_series)) 输出:3.0
请选择适合您需求的方法来计算列表的平均值