python求两个数组中对应元素的平均值
时间: 2024-10-25 21:12:12 浏览: 20
在Python中,如果你有两个数组想要计算它们对应元素的平均值,你可以通过循环或者numpy库来实现。这里是一个简单的例子:
```python
def average_of_arrays(arr1, arr2):
assert len(arr1) == len(arr2), "Arrays must be of the same length"
# 使用循环计算平均值
result = []
for i in range(len(arr1)):
avg = (arr1[i] + arr2[i]) / 2
result.append(avg)
return result
# 或者使用numpy库,更简洁
import numpy as np
def average_of_arrays_numpy(arr1, arr2):
return (np.array(arr1) + np.array(arr2)) / 2
# 示例:
array1 = [1, 2, 3]
array2 = [4, 5, 6]
average_list = average_of_arrays(array1, array2)
average_array = average_of_arrays_numpy(array1, array2)
print("Average values using loop:", average_list)
print("Average values using numpy:", average_array)
```
阅读全文