1 import numpy as np
 2 
 3 # 1、快速排序
 4 '''
 5 1、np.sort(),不改变原先值的顺序,但是在运行时占内存
 6 2、ndarry.sort(),改变原先值的顺序,不占用内存
 7 '''
 8 # 不改变n1的顺序
 9 n1 = np.array([2, 5, 8, 156, 4, 9, 3])
10 n2 = np.sort(n1)
11 # print(n1, n2)
12 '''
13 [  2   5   8   4   9   3 156] [  2   3   4   5   8   9 156]
14 '''
15 # 改变n1的顺序
16 n1.sort()
17 # print(n1)
18 '''
19 [  2   3   4   5   8   9 156]
20 '''
21 # 2、部分排序
22 '''
23 np.partition(a,k)。
24 a:需要排列的值;
25 k:为正时,我们想要得到最小的k个数,为负时,我们想要得到的最大的k个数。但是其余部分不进行排序,但是顺序有可能已经变化
26 '''
27 n1 = np.array([1, 5, 8, 9, 42, 14, 154, 11454, 124, 1215, 3, 245, 7, 15])
28 n3 = np.partition(n1, 4)
29 print(n3)
30 '''
31 [    1     3     5     7     8    14     9    15   124  1215 11454   245 42   154]
32    
33 '''
34 n4 = np.partition(n1, -2)
35 print(n4)
36 '''
37 [    3     1     8     9     7    14     5    15    42   124   154   245   1215 11454]
38 '''
39 # 在排序的同时可以通过切片的方法,取出自己想要的排好序的数据,比如n5 为n1中最大的两个数,n6为n1中最小的4个数
40 n5 = np.partition(n1,-2)[-2:]
41 print(n5)
42 n6 = np.partition(n1,4)[:4]
43 print(n6)

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。