编写一个 Python 程序来查找 numpy 数组项的总和。numpy 的 sum 函数返回数组所有项的总和。我们将此 sum 函数应用于整数数组。
import numpy as np
arr = np.array([10, 20, 40, 70, 90])
total = sum(arr)
print("The Sum of Total Array Item = ", total)
使用 sum 函数输出的 numpy 数组项的总和。
The Sum of Total Array Item = 230
它允许用户输入 numpy ndarray 的大小和项。接下来,我们使用 numpy 的 sum 函数来获取这些数组项的总和。
import numpy as np
arrSumList = []
number = int(input("Enter the Total Array Items = "))
for i in range(1, number + 1):
value = int(input("Enter the %d Array value = " %i))
arrSumList.append(value)
intarrSum = np.array(arrSumList)
total = sum(intarrSum)
print("The Sum of Total Array Item = ", total)

使用 For 循环范围查找 Numpy 数组项总和的 Python 程序
在此 for 循环 (for i in range(len(sumArr))) 中,i 值从数组索引位置 0 迭代到此 sumArr 的长度。在此 for 循环中,我们将每个项添加到总和 (total = total + sumArr[I]) 中。
import numpy as np
sumArr = np.array([10, 60, 30, 40, 70, 95])
total = 0
for i in range(len(sumArr)):
total = total + sumArr[i]
print("The Sum of Total Array Item = ", total)
The Sum of Total Array Item = 305
在此 numpy 示例中,for 循环 (for num in sumArr) 迭代实际的 数组 项,而不是索引位置,并添加这些项。
import numpy as np
sumArr = np.array([10, 30, 50, 70, 90, 120, 150])
total = 0
for num in sumArr:
total = total + num
print("The Sum of Total Array Item = ", total)
The Sum of Total Array Item = 520
使用 while 循环的数组项总和
此程序有助于使用 While 循环计算 Numpy 数组项或元素的总和。
import numpy as np
sumArr = np.array([15, 66, 125, 30, 50, 95])
total = 0
i = 0
while (i < len(sumArr)):
total = total + sumArr[i]
i = i + 1
print("The Sum of Total Array Item = ", total)
The Sum of Total Array Item = 381