如何在 Python 中查詢列表的平均值?


Python 提供 sum 函式用於計算 n 個元素。這裡我們使用此函式,然後計算平均值。

演算法

Step 1: input “size of the list”
Step 2: input “Element”
Step 3: using sum function calculate summation of all numbers.
Step 4: calculate average.

示例程式碼

# Average of a list
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the number ::")
for i in range(int(n)):
   k=int(input(""))
   A.append(int(k))
sm=sum(A)
avg=sm/n
print("SUM = ",sm)
print("AVERAGE = ",avg)

輸出

Enter the size of the List ::5
Enter the number::
10
20
30
40
50
SUM = 150
AVERAGE = 30.0

更新於:2019-07-30

762 次瀏覽

開啟您的職業

完成課程取得認證

立即開始
廣告
© . All rights reserved.