[关闭]
@bergus 2015-12-02T06:02:15.000000Z 字数 544 阅读 1493

python笔记之bisect模块

python python模块


当你决定使用二分搜索时,这个模块会给你带来很大的帮助。

例子

  1. import bisect
  2. L = [1,3,3,6,8,12,15]
  3. x = 3
  4. #在L中查找x,x存在时返回x左侧的位置,x不存在返回应该插入的位置..这是3存在于列表中,返回左侧位置1
  5. x_insert_point = bisect.bisect_left(L,x)
  6. print x_insert_point #1
  7. #在L中查找x,x存在时返回x右侧的位置,x不存在返回应该插入的位置..这是3存在于列表中,返回右侧位置3
  8. x_insert_point = bisect.bisect_right(L,x)
  9. print x_insert_point #3
  10. #将x插入到列表L中,x存在时插入在左侧
  11. x_insort_left = bisect.insort_left(L,x)
  12. print L #[1,3,3,3,6,8,12,15]
  13. #将x插入到列表L中,x存在时插入在右侧
  14. x_insort_rigth = bisect.insort_right(L,x)
  15. print L #[1, 3, 3, 3, 3, 6, 8, 12, 15]
  16. #实际使用中bisect.insort_left与 bisect.insort_right 差别不大,作用基本相同
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注