python bisect(對分) 模塊 排序 詳解

這個排序非常有意思哈, 可以解決插隊的問題,
比如在一個有序的序列中, 有個元素的優先級比較高, 要向前插隊, 但前面還有更高優先級的, 所以就需要插入
更高優先級> 高優先級> 普通級高優先級的位置了

不多說,直接上碼

In [1]: import bisect

In [2]: dir(bisect)
Out[2]:
['__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 'bisect',
 'bisect_left',
 'bisect_right',
 'insort',
 'insort_left',
 'insort_right']

In [3]: s1 = ['a', 'b', 'h']


In [4]: bisect.bisect(s1, 'a')
Out[4]: 1
# 意思是: 將元素'a'插入到s1序列中, 返回應當插入位置的索引
In [5]: bisect.bisect_left(s1, 'h')
Out[5]: 2
# 意思是: 將元素'h'插入到s1序列中, 返回左側插入位置的索引
In [6]: bisect.bisect_right(s1, 'h')
Out[6]: 3
# 意思是: 將元素'h'插入到s1序列中, 返回右則插入位置的索引

In [7]: bisect.insort(s1, 'h')
# 意思是: 將元素'h'插入到s1序列中
In [8]: bisect.insort(s1, 'z')

In [9]: s1
Out[9]: ['a', 'b', 'h', 'h', 'z']

In [10]: bisect.insort_left(s1, 'y')

In [10]: s1
Out[10]: ['a', 'b', 'h', 'h', 'y', 'z']

In [11]: bisect.insort_right(s1, 'y1')

In [12]: s1
Out[12]: ['a', 'b', 'h', 'h', 'y', 'y1', 'z']
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章