用來練手的Python練習題,原題鏈接: python練習實例37
題干: 對10個數進行排序
在我們使用Numpy模塊時,這個問題是非常簡單的,下面放出降序排列和升序排列的代碼:
升序排列
import numpy as npresult = np.zeros(10)
for i in range(result.shape[0]):result[i] = input("輸入一個數:")result = np.sort(result)
print(result)
輸出結果:
降序排列同樣使用np.sort方法,在我們降序排列之后再將矩陣翻轉過來,源代碼如下:
result = np.zeros(10)
for i in range(result.shape[0]):result[i] = input("輸入一個數:")
# 矩陣中括號的相關操作
result = np.sort(result)[::-1]
print(result)
輸出結果如下:
矩陣的中括號操作也是很有趣且重要的一環,有興趣的可以參考我之前的博客:列表的中括號符號小tips。