python學習 bisect模組

2022-06-16 11:12:13 字數 2034 閱讀 7303

1. bisect模組為內建標準庫,它實現了二分法查詢演算法(只要提到二分法查詢,應該優先想到此模組)

2. 主要包含有兩個函式:bisect函式(查詢元素)和insort函式(插入元素)。

場景1:已知乙個有序列表,查詢目標元素的位置索引

import

bisect

#已知乙個有序序列

ordered_list = [23, 34, 59, 78, 99]

des_element = 21res =bisect.bisect(ordered_list, des_element)

print(res) #

res: 0

des_element = 35res =bisect.bisect(ordered_list, des_element)

print(res) #

res: 2

view code

說明:bisect函式會預設返回右側的位置索引,同時bisect函式是bisect_right函式的別名。

場景2:已知乙個有序列表,其中列表中有重複元素,查詢目標元素的位置索引

import

bisect

#已知乙個有序序列

ordered_list = [23, 34, 34, 59, 78, 99]

#bisect函式預設返回右側的位置索引

des_element = 34res =bisect.bisect(ordered_list, des_element)

print(res) #

res: 3

#bisect函式為bisect_right函式的別名

des_element = 34res =bisect.bisect_right(ordered_list, des_element)

print(res) #

res: 3

#bisect_left函式預設返回左側的位置索引

des_element = 34res =bisect.bisect_left(ordered_list, des_element)

print(res) #

res: 1

view code

說明:如果目標元素會在已知有序列表中多次出現,那麼目標元素從已知有序列表的左側或右側插入時結果是不同的。

場景1:替代if-elif語句,例如:判斷考生成績所屬的等級問題。

'''

考試成績的檔位劃分,共分為5個等級:

1. f等級:[0, 60)

2. d等級:[60, 70)

3. c等級:[70, 80)

4. b等級:[80, 90)

5. a等級:[90, 100]

'''import

bisect

def get_result(score: (int, float), score_nodes: list = [60, 70, 80, 90], ranks='

fdcba

') ->str:

#校驗:分數範圍

if score < 0 or score >100:

return

"score的取值範圍:0-100"#

邊界點考慮

if int(score) == 100:

return"a

"loc_index =bisect.bisect(score_nodes, score)

return

ranks[loc_index]

print(get_result(50)) #

res: f

print(get_result(60)) #

res: d

print(get_result(85.5)) #

res: b

print(get_result(100)) #

res: a

view code

python實現二分查詢及bisect模組的簡介

在查詢方面,python中有list.index 的方法。a 2,4,1,9,3 list可以是無序,也可以是有序 a.index 4 找到後返回該值在list中的位置 1這是python中基本的查詢方法,雖然簡單,但是,如果由於其時間複雜度為o n 對於大規模的查詢恐怕是不足以勝任的。二分查詢就是...

Python排序模組 bisect

bisect是python內建模組,主要用於有序序列的插入與查詢!使用這個模組的函式前先確保操作的列表是已排序的 模組的結構 import bisect print dir bisect 結果 builtins cached doc file loader name package spec bis...

python排序模組 bisect

import bisect data 2,4,7,9 使用該模組時需確保操作的列表是已排序的 bisect.insort list,boj 在有序列表中插入元素,不影響原有的排序,插入後的列表仍是有序的 bisect.insort data,3 print data data 2,3,4,7,9 使...