bisect 模块

今天同事说到了一个python的排序模块bisect,觉得挺有趣的,跟大家分享分享。

   先看看模块的结构:

  ![image](https://upload-images.jianshu.io/upload_images/2887744-420c064c8a230416.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

   前面五个属性大家感兴趣可以打出来看看数值,这里就不介绍了。

   先说明的是,使用这个模块的函数前先确保操作的列表是已排序的。

  ![image](https://upload-images.jianshu.io/upload_images/2887744-dd99ff0eb1662e14.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

   先看看 insort  函数:

   ![image](https://upload-images.jianshu.io/upload_images/2887744-af05295c9d6a9bbc.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

   其插入的结果是不会影响原有的排序。

   再看看 bisect  函数:

   ![image](https://upload-images.jianshu.io/upload_images/2887744-84e326277b5e0842.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

   其目的在于查找该数值将会插入的位置并返回,而不会插入。

   接着看 bisect_left 和 bisect_right 函数,该函数用入处理将会插入重复数值的情况,返回将会插入的位置:

   ![image](https://upload-images.jianshu.io/upload_images/2887744-ecead5b9d8eef774.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

   其对应的插入函数是 insort_left  和 insort_right :

   ![image](https://upload-images.jianshu.io/upload_images/2887744-f892854478d6e44f.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

   可见,单纯看其结果的话,两个函数的操作结果是一样的,其实插入的位置不同而已。

你可能感兴趣的:(bisect 模块)