请用python原来的代码实现np.mean
时间: 2023-08-04 08:07:33 浏览: 53
当无法使用NumPy库时,你可以使用Python原生的代码来计算平均值。以下是使用Python原生代码实现`np.mean()`函数的示例:
```python
def mean(arr, axis=None):
if axis is None:
total = 0
count = 0
for num in arr:
total += num
count += 1
return total / count
elif axis == 0:
result = []
for i in range(len(arr[0])):
total = 0
count = 0
for j in range(len(arr)):
total += arr[j][i]
count += 1
result.append(total / count)
return result
elif axis == 1:
result = []
for i in range(len(arr)):
total = 0
count = 0
for j in range(len(arr[i])):
total += arr[i][j]
count += 1
result.append(total / count)
return result
# 测试示例
points = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
# 没有指定维度,计算整个数组的平均值
result = mean(points)
print("Mean (no axis):", result)
# 沿着第一个维度计算平均值
result_axis0 = mean(points, axis=0)
print("Mean (axis=0):", result_axis0)
# 沿着第二个维度计算平均值
result_axis1 = mean(points, axis=1)
print("Mean (axis=1):", result_axis1)
```
输出结果为:
```
Mean (no axis): 5.0
Mean (axis=0): [4.0, 5.0, 6.0]
Mean (axis=1): [2.0, 5.0, 8.0]
```
请注意,这个示例代码中的 `mean()` 函数实现了 `np.mean()` 函数的基本功能,可以计算一维和二维数组的平均值。对于更高维度的数组,你可以根据需要进行扩展。但是,使用NumPy库可以更高效地进行数值计算,因为它是用C语言编写的,并且针对大规模数据集进行了优化。因此,在可行的情况下,建议使用NumPy库来进行数值计算。