bisect是 python 的内置模块,主要用来排序
方法:
bisect.bisect(a, x, lo=0, hi=None)
bisect.bisect_left(a, x, lo=0, hi=None)
bisect.bisect_right(a, x, lo=0, hi=None)
bisect.insort(a, x, lo=0, hi=None)
bisect.insort_left(a, x, lo=0, hi=None)
bisect.insort_right(a, x, lo=0, hi=None)
bisect(a, x, lo=0, hi=None) = bisect_right(a, x, lo=0, hi=None)
insort(a, x, lo=0, hi=None) = insort_right(a, x, lo=0, hi=None)
import bisect
li=[21,4,5,61,45,100]
li.sort()
print(li)
print(bisect.bisect(li,55))
print(bisect.bisect(li,45))
print(bisect.bisect_left(li,45))
print(li)
bisect.insort_right(li,5)
print(li)
说明
[4, 5, 21, 45, 61, 100]
4
4
3
[4, 5, 21, 45, 61, 100]
[4, 5, 5, 21, 45, 61, 100]
可以看到
bisect.bisect系列返回的是插入索引的位置
bisect.insort系列返回的是插入排序后返回的新的有序列表
demo
翻译流畅的python
import bisect
import sys
import bisect
import sys
HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]
ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}'
def demo(bisect_fn):
for needle in reversed(NEEDLES):
position = bisect_fn(HAYSTACK, needle)
offset = position * ' |'
print(ROW_FMT.format(needle, position, offset))
if __name__ == '__main__':
if sys.argv[-1] == 'left':
bisect_fn = bisect.bisect_left
else:
bisect_fn = bisect.bisect
print('DEMO:', bisect_fn.__name__)
print('haystack ->', ' '.join('%2d' % n for n in HAYSTACK))
demo(bisect_fn)
结果
DEMO: bisect_right
haystack -> 1 4 5 6 8 12 15 20 21 23 23 26 29 30
31 @ 14 | | | | | | | | | | | | | |31
30 @ 14 | | | | | | | | | | | | | |30
29 @ 13 | | | | | | | | | | | | |29
23 @ 11 | | | | | | | | | | |23
22 @ 9 | | | | | | | | |22
10 @ 5 | | | | |10
8 @ 5 | | | | |8
5 @ 3 | | |5
2 @ 1 |2
1 @ 1 |1
0 @ 0 0
ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}'说明 format格式化函数
{0:2d} 第0个参数宽度为2
{1:2d} 第1个参数宽度为2
{2} 第2个参数
{0:<2d} 第0个参数,填充右边,宽度为2
d为输出整数的十进制方式
demo2 根据一个分数,查找他所对应的成绩
def grade(score, breakpoints=[60, 70, 80, 90], grades='FDCBA'):
i = bisect.bisect(breakpoints, score)
return grades[i]
[grade(score) for score in [33, 99, 77, 70, 89, 90, 100]]
结果