# python模块介绍- bisect模块维护有序列表

bisect –维护有序列表

bisect模块实现了一个算法用于插入元素到有序列表。在一些情况下，这比反复排序列表或构造一个大的列表再排序的效率更高。Bisect是二分法的意思，这里使用二分法来排序，bisect的源代码是二分法排序的样板。这个模块的代码不到100行。

```import bisect
import random

# Use aconstant seed to ensure that
# the samepseudo-random numbers
# are usedeach time the loop is run.
random.seed(1)

print'New  Pos Contents'
print'---  --- --------'

# Generaterandom numbers and
# insert theminto a list in sorted
# order.
l = []
for i inrange(1, 15):
#产生1-100的随机数
r = random.randint(1, 100)
position = bisect.bisect(l, r)
bisect.insort(l, r)
print'%3d  %3d' % (r, position), l```

#./bisect_example.py

New  Pos Contents

---  --- --------

14    0[14]

85    1[14, 85]

77    1[14, 77, 85]

26    1[14, 26, 77, 85]

50    2[14, 26, 50, 77, 85]

45    2[14, 26, 45, 50, 77, 85]

66    4[14, 26, 45, 50, 66, 77, 85]

79    6[14, 26, 45, 50, 66, 77, 79, 85]

10    0[10, 14, 26, 45, 50, 66, 77, 79, 85]

3    0[3, 10, 14, 26, 45, 50, 66, 77, 79, 85]

84    9[3, 10, 14, 26, 45, 50, 66, 77, 79, 84, 85]

44    4[3, 10, 14, 26, 44, 45, 50, 66, 77, 79, 84, 85]

77    9[3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85]

1    0[1, 3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85]

Bisect模块提供的函数有：

bisect.bisect_left(a,x, lo=0, hi=len(a)) :

bisect.bisect_right(a,x, lo=0, hi=len(a))

bisect.bisect(a, x,lo=0, hi=len(a))

bisect.insort_left(a,x, lo=0, hi=len(a))

bisect.insort_right(a,x, lo=0, hi=len(a))

bisect.insort(a, x,lo=0, hi=len(a))

...     i = bisect(breakpoints, score)

...

>>> [grade(score)for score in [33, 99, 77, 70, 89, 90, 100]]

['F', 'A', 'C','C', 'B', 'A', 'A']

Bisect不像sort一样支持关键字参数，建议如下处理：

```>>> data =[('red', 5), ('blue', 1), ('yellow', 8), ('black', 0)]
>>> data.sort(key=lambdar: r[1])
>>> keys =[r[1] for r in data]         #precomputed list of keys
>>> data[bisect_left(keys,0)]
('black', 0)
>>> data[bisect_left(keys,1)]
('blue', 1)
>>> data[bisect_left(keys,5)]
('red', 5)
>>> data[bisect_left(keys,8)]
('yellow', 8)```

PythonTab微信公众号:

Python技术交流互助群 ( 请勿加多个群 ):