Python 分割算法函数
此模块提供支持,以维护已排序顺序的列表,而不必在插入每个新元素后对列表进行排序。我们将关注两个函数,即 insort_left 和 insort_right。
insort_left
此函数在所需位置插入数字后返回已排序的列表,如果列表中已存在该元素,则该元素将插入到最左边的可能位置。此函数需要 4 个参数,要使用哪个列表、要插入的数字、要考虑的列表中 starting position、要考虑的 ending position。开始和结束位置的默认值为 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("Given list:",listA)
bisect.insort_left(listA,14)
print("Bisect left:\n",listA)
listB = [11,13,23,7,13,15]
print("Given list:",listB)
bisect.insort_right(listB,14,0,4)
print("Bisect righ:\n",listB)输出
运行以上代码,得到以下结果 −
Given list: [11, 13, 23, 7, 13, 15] Bisect left: [11, 13, 23, 7, 13, 14, 15] Given list: [11, 13, 23, 7, 13, 15] Bisect righ: [11, 13, 14, 23, 7, 13, 15]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP