bisect https://docs.python.org/3/library/bisect.htmlPython 标准库中的一个模块非常适合此任务。功能bisect
在模块中bisect
将为您提供该值的插入点的索引。
让我给出一个代码示例bisect
from bisect import bisect
a = 132
b = [0, 10, 30, 60, 100, 150, 210, 280, 340, 480, 530]
print(bisect(b, a))
结果将是5
因为列表是从0开始的,所以实际上它是第6个位置。
您可以知道的是,将结果用于insert
.
index = bisect(b, a)
b.insert(index, a)
或没有中间变量
b.insert(bisect(b, a), a)
Now b
将[0, 10, 30, 60, 100, 132, 150, 210, 280, 340, 480, 530]
.