Use Python bisect module
A, bisect module brief introduction:
Python的bisect模块是内置模块,用于维护有序列表,它采用二分法来排序插入
bisect What are some ways:
# 首先导入bisect包
import bisect
print(dir(bisect))
# 输出结果:
['__builtins__', '__cached__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__',
'bisect', 'bisect_left', 'bisect_right', 'insort',
'insort_left', 'insort_right']
Above these methods, in addition to magic methods, others explain in detail:
bisect : Returns the index element is inserted in the list
my_list = [1, 3, 5, 7, 9]
result = bisect.bisect(my_list, 6)
print(result)
# 输出结果:3 表示插入元素在列表中的下标
bisect_left : default element will be found to the left, to the left of return insert subscript
my_list = [1, 3, 5, 7, 9]
result = bisect.bisect_left(my_list, 6)
print(result)
# 输出结果: 3 同bisect方法
bisect_right : In contrast with bisect_left
my_list = [1, 5, 3, 9, 7]
result = bisect.bisect_right(my_list, 6)
print(result)
# 输出结果: 3
insort : inserts element in the list to the correct location
# 若列表中的元素是有序的话
my_list = [1, 3, 5, 7, 9]
bisect.insort(my_list, 2)
print(my_list)
# 输出结果:[1, 2, 3, 5, 7, 9]
# 若列表中的元素是无序的话,默认插入到最右边
my_list = [2, 3, 1, 5, 7, 4]
bisect.insort(my_list, 6)
print(my_list)
# 输出结果:[2, 3, 1, 5, 7, 4, 6]
insort_left : left interpolation value, the return value None
my_list = [1, 3, 5, 7, 9]
bisect.insort_left(my_list, 2)
print(my_list)
# 输出结果:[1, 2, 3, 5, 7, 9]
insort_right : To insert a value returns None
my_list = [1, 3, 5, 7, 9]
bisect.insort_right(my_list, 6)
print(my_list)
# 输出结果:[1, 3, 5, 6, 7, 9]
insort_left and insort_right: just insert location is different
Second, the use scenarios:
For chestnut to grading, student achievement (0-100) based on student achievement, classified into (ABCDEF):
General operation:
def grade(score):
if score < 60:
return 'F'
elif score < 70:
return 'E'
elif score < 80:
return 'D'
elif score < 90:
return 'C'
elif score < 100:
return 'B'
else:
return 'A'
scores = [59, 60, 72, 82, 85, 90, 98, 100]
result = [grade(item) for item in scores]
print(result)
# 输出结果如下:
['F', 'E', 'D', 'C', 'C', 'B', 'B', 'A']
Operation bisect use of:
-
For example, student achievement classification cut-off point is
[60, 70, 80, 90, 100]
, grades are'FEDCBA'
def grade(score, points=[60, 70, 80, 90, 100], grade="FEDCBA"): item = bisect.bisect(points, score) return grade[item] scores = [101, 60, 72, 82, 85, 90, 98, 100] result = [grade(item) for item in scores] print(result) # 输出结果如下: ['A', 'E', 'D', 'C', 'C', 'B', 'B', 'A']
-
Mall membership points to grade:
def grade(score, points=[60, 70, 80, 90, 100], grade="FEDCBA"): item = bisect.bisect(points, score) print(grade[item]) return grade[item] scores = [1000, 2000, 3000] names = ['普通会员', '中级会员', '高级会员', 'VIP'] values = [999, 1999, 2999, 3001] print([grade(item, points=scores, grade=names) for item in values]) # 输出结果如下:['普通会员', '中级会员', '高级会员', 'VIP']