编写一个 Python示例,以升序对 Numpy 数组项进行排序。numpy 模块中的 sort 函数按升序对数组项进行排序。
# Sort Array Ascending
import numpy as np
orarr = np.array([11, 55, 99, 22, 7, 35, 70])
print("***Sorting Numpy Array in Ascending Order***")
print("Original Array = ", orarr)
orarr.sort()
print("sorted Array = ", orarr)
在这个 Python 示例中,我们使用嵌套 for 循环范围以升序对 numpy 数组项进行排序。在循环中,if 语句(if (orarr[i] > orarr[j])将每个项目与其他数组项目进行比较,并将它们分配给 temp 变量。
# Sort Array Ascending
import numpy as np
orarr = np.array([33, 4, 76, 98, 2, 88, 17, 122, 61])
print("***Sorting Numpy Array in Ascending Order***")
print("Original Array = ", orarr)
length = len(orarr)
for i in range(length):
for j in range(i + 1, length):
if (orarr[i] > orarr[j]):
temp = orarr[i]
orarr[i] = orarr[j]
orarr[j] = temp
print("Array in Ascending Order = ", orarr)
使用循环输出按升序对 Numpy 数组项进行排序
***Sorting Numpy Array in Ascending Order***
Original Array = [ 33 4 76 98 2 88 17 122 61]
Array in Ascending Order = [ 2 4 17 33 61 76 88 98 122]
在这个 Python Numpy Array 示例中,我们创建了一个函数(arrayReverse(orarr)),它以升序对数组项进行排序。
# Sort Array Ascending
import numpy as np
def arrayReverse(orarr):
length = len(orarr)
for i in range(length):
for j in range(i + 1, length):
if (orarr[i] > orarr[j]):
temp = orarr[i]
orarr[i] = orarr[j]
orarr[j] = temp
orarr = np.array([22, 17, 68, 55, 19, 99, 58, 77])
print("***Sorting Numpy Array in Ascending Order***")
print("Original Array = ", orarr)
arrayReverse(orarr)
print("Array in Ascending Order = ", orarr)
按升序排列 Numpy 数组项目输出
***Sorting Numpy Array in Ascending Order***
Original Array = [22 17 68 55 19 99 58 77]
Array in Ascending Order = [17 19 22 55 58 68 77 99]
标签: 推广