[Python]Numpy的sum/greater/all方法應用

Boom
Mar 13, 2021

--

-題目(Topic):

english_score = np.array([55,89,76,65,48,70])

math_score = np.array([60,85,60,68,55,60])

chinese_score = np.array([65,90,82,72,66,77])

上 3 列共六位同學的英文、數學、國文成績,第一個元素代表第一位同學,舉例第一位同學英文 55 分、數學 60 分、國文 65 分,運用上列數據回答下列問題。

  1. 有多少學生英文成績比數學成績高?
  2. 是否全班同學最高分都是國文?

-程式碼(Code):

import numpy as npenglish_score = np.array([55,89,76,65,48,70])math_score = np.array([60,85,60,68,55,60])chinese_score = np.array([65,90,82,72,66,77])#1.有多少學生英文成績比數學成績高?
#np.sum/np.greater
print("第一題:")
print(np.sum(np.greater(english_score,math_score)!=0),'個')
#2.是否全班同學最高分都是國文?
#看國文分數是否都高於math,english的分數/if判斷式
print("第二題:")
if(np.all([np.greater(chinese_score,english_score),np.greater(chinese_score,math_score)])!=0):
print("是")

-結果(Console):

3 個True

-步驟(Step):

  1. 引入numpy這個套件,名稱叫np
import numpy as np

2.宣告英文、數學、國文成績的陣列

english_score = np.array([55,89,76,65,48,70])math_score = np.array([60,85,60,68,55,60])chinese_score = np.array([65,90,82,72,66,77])

3.用np.sum()方法,統計有幾個英文成績比數學成績高的同學

#1.有多少學生英文成績比數學成績高?
#np.sum/np.greater
print("第一題:")
print(np.sum(np.greater(english_score,math_score)!=0),'個')

np.sum(條件式),統計出幾個符合條件式的值

np.greater(),左邊的陣列值比右邊的陣列值還要大則跑出true(也就是1)

在python中 true=1,false=0,所以!=(不等於)0也就表示找結果為true的值,所以這邊其實也可以寫成

print(np.sum(np.greater(english_score,math_score)==1),'個')

在numpy中常用來比較的方法

np.equal() 等於 ==np.not_equal() 不等於 !=np.greater() 大於 >np.greater_equal() 大於或等於 >=np.less() 小於 <np.less() 小於或等於 <=

基本上都是英文直翻,所以蠻好記的

4.用np.all()方法,找出是否(國文成績皆大於數學、英文成績)的結果都為true

print("第二題:")
if(np.all([np.greater(chinese_score,english_score),np.greater(chinese_score,math_score)])!=0):
print("是")

np.all():所有元素為True,即結果為True

就是今天來比較兩個陣列的值,如果結果都為True,結果則為True

print(np.all([[True,True,True],[True,True,True]]))

結果(console)

True

但假如有一個為False,則結果為False

print(np.all([[True,True,False],[True,True,True]]))

結果(console)

False

if的陳述式

if(條件式):(空格)陳述式

一定要空格不然會出錯 ↓ 以下錯誤訊息

File "<ipython-input-39-6374d30214aa>", line 21
print("是")
^
IndentationError: expected an indented block

--

--

Boom
Boom

Written by Boom

Boom Engineer | BOOM ⭐ 程式自學之旅 | 透過筆記釋放記憶體,記錄自己的程式筆記,『內化』成為這段旅程的養分,也分享給路過,正在經歷這趟旅程的你 | Java note begin at 2020.09 | Python note begin at 2021.03

No responses yet