Python中bisect的用法_python

來源:互聯網
上載者:User

本文執行個體講述了Python中bisect的用法,是一個比較常見的實用技巧。分享給大家供大家參考。具體分析如下:

一般來說,Python中的bisect用於操作排序的數組,比如你可以在向一個數組插入資料的同時進行排序。下面的代碼示範了如何進行操作:

import bisectimport randomrandom.seed(1)print('New pos contents')print('-----------------')l=[] for i in range(1,15):  r=random.randint(1,100)  position=bisect.bisect(l,r)  bisect.insort(l,r)  print '%3d %3d'%(r,position),l

輸出結果為:

New pos contents----------------- 14  0 [14] 85  1 [14, 85] 77  1 [14, 77, 85] 26  1 [14, 26, 77, 85] 50  2 [14, 26, 50, 77, 85] 45  2 [14, 26, 45, 50, 77, 85] 66  4 [14, 26, 45, 50, 66, 77, 85] 79  6 [14, 26, 45, 50, 66, 77, 79, 85] 10  0 [10, 14, 26, 45, 50, 66, 77, 79, 85] 3  0 [3, 10, 14, 26, 45, 50, 66, 77, 79, 85] 84  9 [3, 10, 14, 26, 45, 50, 66, 77, 79, 84, 85] 44  4 [3, 10, 14, 26, 44, 45, 50, 66, 77, 79, 84, 85] 77  9 [3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85] 1  0 [1, 3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85]

可以看到,在插入這些隨機數的時候數組同時進行了排序。不過其中有一些重複的元素,比如上面的77,77。你可以對這些重複元素的順序進行設定,如果希望重複的元素出現在與他相同的元素左邊就是用bisect_left,否則就是用bisect_right,相應的使用insort_left和insort_right。比如下面的代碼,我們可以看到出現重複的元素索引變化:

import bisectimport randomrandom.seed(1)print('New pos contents')print('-----------------')l=[] for i in range(1,15):  r=random.randint(1,100)  position=bisect.bisect_left(l,r)  bisect.insort_left(l,r)  print '%3d %3d'%(r,position),l

輸出結果為:

New pos contents----------------- 14  0 [14] 85  1 [14, 85] 77  1 [14, 77, 85] 26  1 [14, 26, 77, 85] 50  2 [14, 26, 50, 77, 85] 45  2 [14, 26, 45, 50, 77, 85] 66  4 [14, 26, 45, 50, 66, 77, 85] 79  6 [14, 26, 45, 50, 66, 77, 79, 85] 10  0 [10, 14, 26, 45, 50, 66, 77, 79, 85] 3  0 [3, 10, 14, 26, 45, 50, 66, 77, 79, 85] 84  9 [3, 10, 14, 26, 45, 50, 66, 77, 79, 84, 85] 44  4 [3, 10, 14, 26, 44, 45, 50, 66, 77, 79, 84, 85] 77  8 [3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85] 1  0 [1, 3, 10, 14, 26, 44, 45, 50, 66, 77, 77, 79, 84, 85]

此函數bisect.bisect(list,key) ,猶如java裡的TreeMap的tailMap(fromkey)。

希望本文所述對大家的Python程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.