简体   繁体   English

在列表中查找下一个最接近的数字

[英]Finding the next closest number in a list

I have a list:我有一个清单:

lst = [100, 210, 330, 460, 600, 750, 910, 1080, 1260]

and a given number 470和给定的数字470

I want to find the next upper bound of the interval between its two closest numbers... This would give 600 because it is the next closest number.我想找到它的两个最接近的数字之间的间隔的下一个上限......这将给出600 ,因为它是下一个最接近的数字。

If it were 670 I would get 750 .如果是670我会得到750

I have lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))] which is giving the closet number regardless if it is the upper bound.我有lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))]给出壁橱号码,无论它是否是上限。

You can use bisect.bisect_left which gives you the left most insertion index (given the list is sorted which your post seems to indicate it is) in logarithmic time:您可以使用bisect.bisect_left以对数时间为您提供最左边的插入索引(假设列表已排序,您的帖子似乎表明它是这样的):

from bisect import bisect_left

A[bisect_left(A, 460)]
460
>>> A[bisect_left(A, 470)]
600
>>> A[bisect_left(A, 670)]
750

This will raise an IndexError for numbers greater than 1260 .对于大于1260的数字,这将引发IndexError

filter(lambda x: x>=460, A).__next__() # 460 filter(lambda x: x>=470, A).__next__() # 600 filter(lambda x: x>=670, A).__next__() # 750

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM