寫一個 Python 程序來求 numpy 數組項的和。numpy sum 函數返回所有數組項的總和。我們在整數數組上使用這個和函數。
import numpy as np
arr = np.array([10, 20, 40, 70, 90])
total = sum(arr)
print("The Sum of Total Array Item = ", total)
Python Numpy 數組項的和使用求和函數輸出
The Sum of Total Array Item = 230
它允許用戶輸入 NumPy 數組大小和項目。接下來,我們使用 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)
Python Numpy 數組項求和輸出
Enter the Total Array Items = 4
Enter the 1 Array value = 20
Enter the 2 Array value = 5090
Enter the 3 Array value = 20
Enter the 4 Array value = 54
The Sum of Total Array Item = 5184
在這個 for 循環中(對於 i in range(len(sumArr)),I 值從數組索引位置 0 迭代到這個 sumArr 的長度。在這個 for 循環中,我們將每個項目添加到總數中(總數=總數+sumrr[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
在這個 Python numpy 數組示例中,for 循環(在 sumArr 中為 num)迭代實際的數組項,而不是索引位置,並添加這些項。
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
Python 程序使用 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)
原創文章,作者:WUAOP,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/126499.html