Python bisect模块
可以查看官方文档
http://code.activestate.com/recipes/577197-sortedcollection/.
用bisect.bisect来搜索
bisect.bisect(a, x, lo=0, hi=None)
lo hi是索引范围
在一个有序的a里面查找x应该在哪
下面这个例子可能有点多,希望能看一下理解
def demo(func):
for needle in reversed(NEEDLES):
position = func(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.bisect默认就是bisect.bisect_right
bisect_fn = bisect.bisect_right
print("DEMO:", bisect_fn.__name__)
print("haystack ->", " ".join("%2d" % n for n in HAYSTACK))
demo(bisect_fn)
"""这里的解释是,cmd命令行里最后一个参数是left,那么默认插入左边bisect.bisect(大范围, 小元素)"""
比如$ python3 demo.py left # 这样的话下面结果相同数值就会判断在左边
输出结果
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
bisect.insort插入新元素
bisect.insort(seq, item, lo=0, hi=None) 将item插入新元素进seq( lo, hi是索引范围)
同理数值相同的时候left插入左边,right插入右边
比如:
import bisect
import random
size = 7
random.seed(1729)
my_list = []
for i in range(size):
new_item = random.randrange(size*2)
bisect.insort(my_list, new_item)
print('%2d ->' % new_item, my_list)
10 -> [10]
0 -> [0, 10]
6 -> [0, 6, 10]
8 -> [0, 6, 8, 10]
7 -> [0, 6, 7, 8, 10]
2 -> [0, 2, 6, 7, 8, 10]
10 -> [0, 2, 6, 7, 8, 10, 10]
好啦介绍完啦