当前位置:Gxlcms > Python > Python中的bisect

Python中的bisect

时间:2021-07-01 10:21:17 帮助过:72人阅读

Python 中的bisect用于操作排序的数组,比如你可以在向一个数组插入数据的同时进行排序。下面的代码演示了如何进行操作:

输出结果为:

  1. New pos contents
  2. -----------------
  3. 14 0 [14]
  4. 85 1 [14, 85]
  5. 77 1 [14, 77, 85]
  6. 26 1 [14, 26, 77, 85]
  7. 50 2 [14, 26, 50, 77, 85]
  8. 45 2 [14, 26, 45, 50, 77, 85]
  9. 66 4 [14, 26, 45, 50, 66, 77, 85]
  10. 79 6 [14, 26, 45, 50, 66, 77, 79, 85]
  11. 10 0 [10, 14, 26, 45, 50, 66, 77, 79, 85]
  12. 3 0 [3, 10, 14, 26, 45, 50, 66, 77, 79, 85]
  13. 84 9 [3, 10, 14, 26, 45, 50, 66, 77, 79, 84, 85]
  14. 44 4 [3, 10, 14, 26, 44, 45, 50, 66, 77, 79, 84, 85]
  15. 77 9 [3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85]
  16. 1 0 [1, 3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85]


可以看到,在插入这些随机数的时候数组同时进行了排序。不过其中有一些重复的元素,比如上面的77,77。你可以对这些重复元素的顺序进行设置,如果希望重复的元素出现在与他相同的元素左边就是用bisect_left,否则就是用bisect_right,相应的使用insort_left和insort_right。比如下面的代码,我们可以看到出现重复的元素索引变化:

  1. import bisect
  2. import random
  3. random.seed(1)
  4. print('New pos contents')
  5. print('-----------------')
  6. l=[]
  7. for i in range(1,15):
  8. r=random.randint(1,100)
  9. position=bisect.bisect_left(l,r)
  10. bisect.insort_left(l,r)
  11. print '%3d %3d'%(r,position),l

输出结果为:

  1. New pos contents
  2. -----------------
  3. 14 0 [14]
  4. 85 1 [14, 85]
  5. 77 1 [14, 77, 85]
  6. 26 1 [14, 26, 77, 85]
  7. 50 2 [14, 26, 50, 77, 85]
  8. 45 2 [14, 26, 45, 50, 77, 85]
  9. 66 4 [14, 26, 45, 50, 66, 77, 85]
  10. 79 6 [14, 26, 45, 50, 66, 77, 79, 85]
  11. 10 0 [10, 14, 26, 45, 50, 66, 77, 79, 85]
  12. 3 0 [3, 10, 14, 26, 45, 50, 66, 77, 79, 85]
  13. 84 9 [3, 10, 14, 26, 45, 50, 66, 77, 79, 84, 85]
  14. 44 4 [3, 10, 14, 26, 44, 45, 50, 66, 77, 79, 84, 85]
  15. 77 8 [3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85]
  16. 1 0 [1, 3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85]

此函数bisect.bisect(list,key) ,犹如java里的TreeMap的tailMap(fromkey)

人气教程排行