Python中的等分算法功能

该模块提供了对按排序顺序维护列表的支持,而无需在每次插入新元素后对列表进行排序。我们将重点介绍两个函数,即insort_left和insort_right。

insort_left

该函数在所需位置插入数字后返回排序后的列表,如果列表中已存在该元素,则该元素将插入到最左侧的位置。此函数有4个参数,必须使用的列表,要插入的编号,要考虑的列表中的开始位置,必须考虑的结束位置。开始和结束位置的默认值分别是0和字符串的长度。

这类似于inser_left,不同之处在于,在插入现有条目之后不维护严格排序顺序的情况下插入了新元素。

语法

bisect.insort_left(a, x, lo=0, hi=len(a))
bisect.insort_left(a, x, lo=0, hi=len(a))
a is the given sequence
x is the number to be inserted

示例

在下面的示例中,我们看到了一个列表,并首先对其应用了bisect.insort_left函数。

import bisect

listA = [11,13,23,7,13,15]
print("给定列表:",listA)
bisect.insort_left(listA,14)
print("Bisect left:\n",listA)

listB = [11,13,23,7,13,15]
print("给定列表:",listB)
bisect.insort_right(listB,14,0,4)
print("Bisect righ:\n",listB)

输出结果

运行上面的代码给我们以下结果-

给定列表: [11, 13, 23, 7, 13, 15]
Bisect left:
   [11, 13, 23, 7, 13, 14, 15]
给定列表: [11, 13, 23, 7, 13, 15]
Bisect righ:
   [11, 13, 14, 23, 7, 13, 15]