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