如何用Python编写程序来计算两个数组的元素和及它们的对应元素之差?
时间: 2024-10-26 16:16:57 浏览: 77
在Python中,你可以通过循环和条件语句来计算两个数组的元素和以及对应元素的差。这里是一个简单的例子:
```python
def calculate_arrays(arr1, arr2):
# 确保两个数组长度相等
if len(arr1) != len(arr2):
return "Error: Arrays must have the same length."
# 初始化结果数组
result_sum = []
result_diff = []
# 遍历两个数组
for i in range(len(arr1)):
# 计算元素和
sum_element = arr1[i] + arr2[i]
result_sum.append(sum_element)
# 计算元素差
diff_element = arr1[i] - arr2[i]
result_diff.append(diff_element)
return result_sum, result_diff
# 示例数组
arr1 = [1, 2, 3, 4]
arr2 = [5, 6, 7, 8]
# 调用函数并打印结果
sum_result, diff_result = calculate_arrays(arr1, arr2)
print("Element-wise sum:", sum_result)
print("Element-wise difference:", diff_result)
阅读全文