直接上码
>>> import bisect
>>> list1 = [1,2,3,4, 6, 7, 10] // 这是一个有序序列
>>> bisect.bisect(list1, 5) // 返回5应该在list1中的索引
4
>>> list1 // 但list1没变
[1, 2, 3, 4, 6, 7, 10]
>>> bisect.insort(list1, 5) // 这里是insort, 不是insert,
>>> list1
[1, 2, 3, 4, 5, 6, 7, 10] // list1 结果变了
>>> list1.insert(0, 8) // list的insert操作,无特殊意义
>>> list1
[8, 1, 2, 3, 4, 5, 6, 7, 10]
>>> list1.insert(8, 8)
>>> list1
[8, 1, 2, 3, 4, 5, 6, 7, 8, 10]
>>>
bisect.insort 可以插入有序序列中应当出现的位置,不需要指定位置,
list.insert可以插入list中任何一个位置,list可以是无序的,
代码详解一哈
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']
小应用场景:
import bisect
def get_score_level(score, scores=(60, 70, 80, 90), grades="EDCBA"):
position = bisect.bisect(scores, score)
return grades[position]
print(get_score_level(65))
可以不用那么一推if else了