bisect排序模块

翻FluentPython的时候发现有这个鬼玩意———bisect。不清楚是干嘛的,总结一下贴出来。
写完之后感觉这个鬼玩意不是很厉害,只是插入数据可以自动查到相应的位置,并且可以找到对应的位置。(不是index的值)

首先看看模块的结构:

In [1]: import bisect

In [2]: dir(bisect)
Out[2]:
['__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'bisect',
 'bisect_left',
 'bisect_right',
 'insort',
 'insort_left',
 'insort_right']

In [3]:

使用:

准备一个已经排序果的列表:

In [3]: data = [3, 5, 2, 6, 1, 8, 4]

In [4]: data.sort()

In [5]: data
Out[5]: [1, 2, 3, 4, 5, 6, 8]

bisect.inosrt()

inosrt()方法是插入数据。
In [15]: data
Out[15]: [-2, 1, 2, 3, 4, 5, 6, 8, 19]

In [16]: bisect.insort(data, 100)

In [17]: data
Out[17]: [-2, 1, 2, 3, 4, 5, 6, 8, 19, 100]  # insort会将数字按照大小放在列表中

bisect.bisect()

bisect()方法返回的是所要查询的数字所在的位置,并不会插入数据。

In [33]: list_temp
Out[33]: [3, 20, 34, 43, 45, 54]

In [34]: bisect.bisect(list_temp, 3)  # 查询数字3的位置,返回的1是在一个位置
Out[34]: 1

In [35]: bisect.bisect(list_temp, 54) # 查询数字54的位置,返回的是6,是第六个数字
Out[35]: 6

In [36]: bisect.bisect(list_temp, 20) # 同上
Out[36]: 2

In [37]: bisect.bisect(list_temp, -3)    # 查询一个不存在的, 小于现有数字的数字,返回的0
Out[37]: 0

In [38]: bisect.bisect(list_temp, 99)    # 查询一个不存在,且比现有数字大的数字,返回依然是6, 这就尴尬了,怎么区分。。。。 
Out[38]: 6

bisect.insort_left(), insort_right()

这2个方法是插入重复数据,并且指定好是左边还是右边。

In [41]: list_temp
Out[41]: [3, 20, 21, 34, 43, 45, 54]

In [42]: bisect.insort_left(list_temp, 21)

In [43]: list_temp
Out[43]: [3, 20, 21, 21, 34, 43, 45, 54]

bisect_left, bisect_right

这2种方法会返回所插入的位置,并不插入数据。(那和bisect.bisect()有什么区别…..)
貌似是没有区别的。
In [52]: list_temp
Out[52]: [3, 20, 21, 21, 34, 43, 45, 54]

In [53]: bisect.bisect_left(list_temp, 52)
Out[53]: 7

In [54]: list_temp
Out[54]: [3, 20, 21, 21, 34, 43, 45, 54]

以上完毕,总体感觉不是很牛的方法。不过,倒是有点用,示例:

#coding=utf8
import bisect
grades = 'FEDCBA'
breakpoints = [3, 20, 34, 43, 45, 54]


def grade(totle):
    """
    breakpoints是原数据,totle是要查询的数据
    bisect.bisect(breakpoints, totle) 返回的是列表的索引值
    :param totle:
    :return:
    """
    print(grades[bisect.bisect(breakpoints, totle)])
grade(45)

调用函数grade,可以找到对应的字母。
输出结果:
D:\ProSoft\Anaconde\python.exe D:/file_git/example_code/02-arry-seq/bisect_test.py
B