真實情境中的 Python 模組化
在投影片中,我們介紹了 3 種用 Python 撰寫模組化程式碼的方式:packages、classes 與 methods。參考用的範例程式碼如下。
# Import the pandas PACKAGE
import pandas as pd
# Create some example data
data = {'x': [1, 2, 3, 4],
'y': [20.1, 62.5, 34.8, 42.7]}
# Create a dataframe CLASS object
df = pd.DataFrame(data)
# Use the plot METHOD
df.plot('x', 'y')
在這個練習中,你將使用熱門 package numpy 的一個 class 與一個 method。
本練習屬於課程
Python 的軟體工程原則
練習說明
- 完成
import陳述式以載入numpypackage。 - 使用
numpy的arrayclass 來定義arr。 - 使用
arr的sortmethod 來排序這個numpy陣列。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# import the numpy package
import ____ as np
# create an array class object
arr = np.____([8, 6, 7, 5, 3, 0, 9])
# use the sort method
arr.____()
# print the sorted array
print(arr)