中间平分 - Python 中的数组中间平分算法


在长列表中每次插入后执行排序操作在时间消耗方面可能很昂贵。中间平分模块确保列表在插入后自动排序。出于此目的,它使用中间平分算法。该模块具有以下函数

bisect_left()

此方法找到用于保持排序顺序的列表中给定元素的插入点。如果它已存在于列表中,则插入点将在任何现有项之前(左边)。返回值可以用作 list.insert() 的第一个参数

bisect_right()

此方法与 bisect_left() 类似,但返回的插入点在列表中任何现有项的后面(右边)。

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

bisect.insort_left()

此方法按排序顺序在 a 中插入给定值。这等价于 a.insert(bisect.bisect_left(a, x, lo, hi), x)

bisect.insort_right()

bisect.insort()

两个方法都类似于 insort_left(),但在列表中插入给定值在相同值的任何现有项后面。

示例

>>> nums = [45,21,34,87,56,12,5,98,30,63]
>>> nums.sort()
>>> nums
[5, 12, 21, 30, 34, 45, 56, 63, 87, 98]
>>> import bisect
>>> p = bisect.bisect_left(nums,50)
>>> p
6
>>> nums.insert(p,50)
>>> nums
[5, 12, 21, 30, 34, 45, 50, 56, 63, 87, 98]
>>> bisect.insort(nums, 29)
>>> nums
[5, 12, 21, 29, 30, 34, 45, 50, 56, 63, 87, 98]

更新日期: 2019 年 7 月 30 日

532 次浏览

开启您的 职业生涯

完成课程获取认证

开始
广告