参考代码:
1 newlist = [37, 99, 73, 48, 47, 40, 40, 25, 99, 51] 2 newlist = sorted(newlist) # [25, 37, 40, 40, 47, 48, 51, 73, 99, 99] 3 4 def inster_sort(newlist, num): 5 l = newlist[:] 6 low = 0 7 high = len(l) 8 while low < high: 9 mid = (high + low) // 2 10 if num < newlist[mid]: 11 high = mid 12 else: 13 low = mid + 1 14 l.insert(high,num) 15 # l.insert(low,num) 16 return l 17 18 # print(inster_sort(newlist, 100)) 19 l = newlist 20 for i in [10, 100,50,98,100,49,40,40]: 21 l = inster_sort(l, i) 22 print(l) 23 print('____------__________------') 24 for i in [10, 100,50]: 25 l = inster_sort(newlist, i) 26 print(l)
结果打印:
1 [10, 25, 37, 40, 40, 47, 48, 51, 73, 99, 99] 2 [10, 25, 37, 40, 40, 47, 48, 51, 73, 99, 99, 100] 3 [10, 25, 37, 40, 40, 47, 48, 50, 51, 73, 99, 99, 100] 4 [10, 25, 37, 40, 40, 47, 48, 50, 51, 73, 98, 99, 99, 100] 5 [10, 25, 37, 40, 40, 47, 48, 50, 51, 73, 98, 99, 99, 100, 100] 6 [10, 25, 37, 40, 40, 47, 48, 49, 50, 51, 73, 98, 99, 99, 100, 100] 7 [10, 25, 37, 40, 40, 40, 47, 48, 49, 50, 51, 73, 98, 99, 99, 100, 100] 8 [10, 25, 37, 40, 40, 40, 40, 47, 48, 49, 50, 51, 73, 98, 99, 99, 100, 100] 9 ____------__________------ 10 [10, 25, 37, 40, 40, 47, 48, 51, 73, 99, 99] 11 [25, 37, 40, 40, 47, 48, 51, 73, 99, 99, 100] 12 [25, 37, 40, 40, 47, 48, 50, 51, 73, 99, 99]
2、bisect 模块:
举例:
1 import bisect 2 newlist = [37, 99, 73, 48, 47, 40, 40, 25, 99, 51] 3 newlist = sorted(newlist)# [25, 37, 40, 40, 47, 48, 51, 73, 99, 99] 4 n = bisect.bisect(newlist, 20) 5 print(n) 6 n = bisect.bisect_left(newlist, 40) 7 print(n) 8 bisect.insort(newlist, 40) 9 print(newlist)
打印:
0 2 [25, 37, 40, 40, 40, 47, 48, 51, 73, 99, 99]
bisect模块介绍:
3、举例:
1 def foo(score): 2 scorelst = [60, 70, 80, 90, 100] 3 scores = 'edcba' 4 return scores[bisect.bisect(scorelst, score)] 5 print(foo(80))