从区间列表中确定值的位置(合成溶液)

2024-04-26 05:35:55 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我有一个增加值的列表l

import numpy as np
l=np.linspace(0.,1.,10)

对于一个数a=0.225,我想找到索引i,这样l[i]<a<l[i+1]。当然,我可以

for j in range(len(l)-1):
    if l[j]<a<l[j+1]:
        i=j
        break

但是有没有更综合的方法呢?你知道吗


Tags: 方法inimportnumpy列表forlenif
2条回答

对于纯python解决方案,有^{}模块:

>>> from bisect import bisect_left
>>> a = list(range(1, 10))
>>> bisect_left(a, 3.5)
3

或与numpy:

>>> from bisect import bisect_left
>>> import numpy as np
>>> l = np.linspace(0, 1, 10)
>>> bisect_left(l, 0.225)
3

bisect.bisect_left(a, x, lo=0, hi=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.

如注释中所述,对于要排序的l,我们可以使用np.searchsorted-

np.searchsorted(l,a,'right')-1

或与np.digitize-

np.digitize(a,l,right=True)-1

相关问题 更多 >