Python bisect 笔记

bisect.bisect_left(axlo=0hi=len(a))

Locate the insertion point for x in a to maintain sorted order. The parameters lo and hi may be used to specify a subset of the list which should be considered; by default the entire list is used. If x is already present in a, the insertion point will be before (to the left of) any existing entries. The return value is suitable for use as the first parameter to list.insert() assuming that a is already sorted.

The returned insertion point i partitions the array a into two halves so that all(val < x for val in a[lo:i]) for the left side and all(val >= x for val in a[i:hi])for the right side.

bisect.bisect_right(axlo=0hi=len(a))bisect.bisect(axlo=0hi=len(a))

Similar to bisect_left(), but returns an insertion point which comes after (to the right of) any existing entries of x in a.

The returned insertion point i partitions the array a into two halves so that all(val <= x for val in a[lo:i]) for the left side and all(val > x for val in a[i:hi])for the right side.

```python

import bisect


print(bisect.bisect_left(ls,0))

寻找 elem出现的最左位置,或者寻找第一个比x大的index

example:

ls = [-1,1,1,1,1,1,1,2,3,4,5]

寻找第一个比0大的数字

bisect_left(ls,0)

寻找1第一次出现的地方

bisect_left(ls,1)

right同理


print(bisect.bisect_right(ls,1))

```

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容