Python bisect模塊原理及常見(jiàn)實(shí)例
1. 模塊介紹
1. bisect模塊為內(nèi)置標(biāo)準(zhǔn)庫(kù),它實(shí)現(xiàn)了二分法查找算法(只要提到二分法查找,應(yīng)該優(yōu)先想到此模塊)
2. 主要包含有兩個(gè)函數(shù):bisect函數(shù)(查找元素)和insort函數(shù)(插入元素)。
2. 常用方法介紹
場(chǎng)景1:已知一個(gè)有序列表,查找目標(biāo)元素的位置索引
import bisect# 已知一個(gè)有序序列ordered_list = [23, 34, 59, 78, 99]des_element = 21res = bisect.bisect(ordered_list, des_element)print(res) # res: 0des_element = 35res = bisect.bisect(ordered_list, des_element)print(res) # res: 2
說(shuō)明:bisect函數(shù)會(huì)默認(rèn)返回右側(cè)的位置索引,同時(shí)bisect函數(shù)是bisect_right函數(shù)的別名。
場(chǎng)景2:已知一個(gè)有序列表,其中列表中有重復(fù)元素,查找目標(biāo)元素的位置索引
import bisect# 已知一個(gè)有序序列ordered_list = [23, 34, 34, 59, 78, 99]# bisect函數(shù)默認(rèn)返回右側(cè)的位置索引des_element = 34res = bisect.bisect(ordered_list, des_element)print(res) # res: 3# bisect函數(shù)為bisect_right函數(shù)的別名des_element = 34res = bisect.bisect_right(ordered_list, des_element)print(res) # res: 3# bisect_left函數(shù)默認(rèn)返回左側(cè)的位置索引des_element = 34res = bisect.bisect_left(ordered_list, des_element)print(res) # res: 1
說(shuō)明:如果目標(biāo)元素會(huì)在已知有序列表中多次出現(xiàn),那么目標(biāo)元素從已知有序列表的左側(cè)或右側(cè)插入時(shí)結(jié)果是不同的。
3. 場(chǎng)景應(yīng)用
場(chǎng)景1:替代if-elif語(yǔ)句,例如:判斷考生成績(jī)所屬的等級(jí)問(wèn)題。
’’’ 考試成績(jī)的檔位劃分,共分為5個(gè)等級(jí): 1. F等級(jí):[0, 60) 2. D等級(jí):[60, 70) 3. C等級(jí):[70, 80) 4. B等級(jí):[80, 90) 5. A等級(jí):[90, 100]’’’import bisectdef get_result(score: (int, float), score_nodes: list = [60, 70, 80, 90], ranks=’FDCBA’) -> str: # 校驗(yàn):分?jǐn)?shù)范圍 if score < 0 or score >100: return 'score的取值范圍:0-100' # 邊界點(diǎn)考慮 if int(score) == 100: return 'A' loc_index = bisect.bisect(score_nodes, score) return ranks[loc_index]print(get_result(50)) # res: Fprint(get_result(60)) # res: Dprint(get_result(85.5)) # res: Bprint(get_result(100)) # res: A
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python實(shí)現(xiàn)讀取類(lèi)別頻數(shù)數(shù)據(jù)畫(huà)水平條形圖案例2. python中PyQuery庫(kù)用法分享3. python操作數(shù)據(jù)庫(kù)獲取結(jié)果之fetchone和fetchall的區(qū)別說(shuō)明4. php使用正則驗(yàn)證密碼字段的復(fù)雜強(qiáng)度原理詳細(xì)講解 原創(chuàng)5. Ajax實(shí)現(xiàn)頁(yè)面無(wú)刷新留言效果6. python 爬取嗶哩嗶哩up主信息和投稿視頻7. 關(guān)于HTML5的img標(biāo)簽8. PHP獲取時(shí)間戳等相關(guān)函數(shù)匯總9. CSS3實(shí)現(xiàn)動(dòng)態(tài)翻牌效果 仿百度貼吧3D翻牌一次動(dòng)畫(huà)特效10. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能
