<
>

Python中bisect的使用方法

2020-06-25 08:12:28 来源:易采站长站 作者:易采站长站整理


>>> def test_index():
... return lst.index(val)
...
>>> t4 = timeit.timeit("test_index()", setup="from __main__ import test_index")
>>> t4
518.1656223725007

可以看到,如果用Python原生的list.index()执行1000000,需要500秒,相比之前的二分查找,性能简直慢到恐怖

用bisect.insort插入新元素

排序很耗时,因此在得到一个有序序列之后,我们最好能够保持它的有序。bisect.insort就是为这个而存在的

insort(seq, item)把变量item插入到序列seq中,并能保持seq的升序顺序


import random
from random import randint
import bisect

lst = []SIZE = 10
random.seed(5)
for _ in range(SIZE):
item = randint(1, SIZE)
bisect.insort(lst, item)
print('%2d ->' % item, lst)

输出:

10 -> [10] 5 -> [5, 10] 6 -> [5, 6, 10] 9 -> [5, 6, 9, 10] 1 -> [1, 5, 6, 9, 10] 8 -> [1, 5, 6, 8, 9, 10] 4 -> [1, 4, 5, 6, 8, 9, 10] 1 -> [1, 1, 4, 5, 6, 8, 9, 10] 3 -> [1, 1, 3, 4, 5, 6, 8, 9, 10] 2 -> [1, 1, 2, 3, 4, 5, 6, 8, 9, 10]

您可能感兴趣的文章:Python实现二分查找与bisect模块详解python中bisect模块用法实例Python中bisect的用法

暂时禁止评论

微信扫一扫

易采站长站微信账号