如何找到数字落在一组连续整数之间的位置

How to find the positions that a number falls in-between in a set of sequential integers

我有一个数字变量和一组连续的整数。随着 number 变量的变化,我需要记录 number 变量在连续整数集中的位置。

例如,如果我的整数集是:

li = [20,21,22,23,24,25,26,27,28,29,30]

数字变量为:

num = 22.74

我想要的输出是列表中 num 介于两者之间的位置:

2,3

我知道 li.index(22) 会 return 这个位置,但前提是该确切项目在列表中。如果数字介于项目之间,则无法找到如何找到位置。

我想象一个 for 循环,通过检查 num 是否落在这两个整数之间来比较 num 与列表中的每个相邻位置项可以解决它。类似于:

for x and the following item in li:
    if x < num < the following item:
        positionone = x
        positiontwo = the following item
    else:
        continue

只是无法完成其工作原理,主要是通过获取列表的下一个位置来替换“以下项目”。也许有更好的方法来解决这个问题?任何帮助深表感谢!谢谢!

你的基本逻辑很接近。您需要遍历列表。如果您使用索引而不是值来执行此操作,您将能够检索到您想要的位置。 你的基本逻辑没问题。

for idx in range(len(li)-1):
    if li[idx] < num < li[idx+1]:
        pos1, pos2 = idx, idx+1

鉴于此,我希望你能解决特殊情况下的平等问题,对吧?

我不会触及关于 num 是否为整数的歧义。但我会给你所需的工具来回答你的问题。

lohi分别为您兴趣的下限和上限。然后,要获得这两者之间的数字的索引是这样完成的:

indices = [i for i, x in enumerate(li)
           if lo < x < hi]

请注意,我在那里使用了两次 <。如果您希望下限具有包容性,请将第一个 < 替换为 <=。同样,如果您希望包含上限,请将第二个 < 替换为 <=。或者非常笼统:

def indices_between(iterable, lo, hi, include_lo=False, include_hi=False):
    lo_req = (lambda x: lo <= x) if include_lo else (lambda x: lo < x)
    hi_req = (lambda x: x <= hi) if include_hi else (lambda x: x < hi)
    return [i for i, x in enumerate(iterable)
            if lo_req(x) and hi_req(x)]

您可以将您的数字与每个元素进行比较,如果当前元素大于您的数字则中断循环:

for index, current_element in enumerate(li):
    if current_element > num:
        position_one, position_two = index - 1 if index else index, index
        break
else:
    position_one, position_two = index, index

执行此操作的数学方法是从列表中减去数字并检查两个最小绝对值。如果 li 是一个 numpy 数组,您可以在一行中执行此操作:

li = np.array(li)
interval = sorted(np.abs(li-num).argsort()[:2])