python求平均數及打印出低於平均數的值列表


剛學Python的時候還是要多動手進行一些小程序的編寫,要持續不斷的進行,知識才能掌握的牢。今天就講一下Python怎么求平均數,及打印出低於平均數的數值列表

 

 1 方法一:
 2 scores1 =  [91, 95, 97, 99, 92, 93, 96, 98]
 3 sum = 0
 4 scores2 = []
 5 for score in scores1:
 6     sum = sum + score
 7     average = sum/len(scores1)
 8 print('平均成績是:{}'.format(average)) 
 9 
10 for score in scores1:
11     if score < average:
12         scores2.append(score) # 少於平均分的成績放到新建的空列表中
13 print('低於平均成績的有:{}'.format(scores2))  # format是格式化用的
14 
15 方法二:使用科學計算庫的python 外接庫--numpy,其中mean是庫中求平均數用的,需要先在python中通過pip下載安裝
16 import numpy as np
17 scores1 =  [91, 95, 97, 99, 92, 93, 96, 98]
18 scores2 = []
19 average = np.mean(scores1)  # mean意思求平均數的函數
20 print('平均成績是:{}'.format(average))
21 
22 for score in scores1:
23     if score < average:
24         scores2.append(score) # 少於平均分的成績放到新建的空列表中
25 print('低於平均成績的有:{}'.format(scores2))  # format是格式化用的
26 
27 方法三:NumPy數組的操作,也可以打印出低於平均數的列表
28 scores3 = np.array(scores1)
29 print(' 低於平均成績的有:{}'.format(scores3[scores3<average]))

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM