繁体   English   中英

有效地查找数量最小的索引,该索引大于大型排序列表中的某个值

[英]Efficiently find index of smallest number larger than some value in a large sorted list

如果我有一个很长的排序数字列表,并且我想找到大于某个值的最小元素的索引,是否有比在整个列表上使用二进制搜索更有效地实现它的方法?

例如:

import random
c = 0
x = [0 for x in range(50000)]

for n in range(50000):
    c += random.randint(1,100)
    x[n] = c

在x中找到小于某个数字z的最大元素的位置的最有效方法是什么

我知道您已经可以:

import bisect
idx = bisect.bisect(x, z)

但是,假设此操作可以执行多次,那么还有比二进制搜索更有效的方法吗? 由于列表的范围很大,因此创建所有可能整数的字典将占用过多内存。 是否可以创建一个较小的列表(例如每5000个数字),并使用该列表来加快对较大列表的特定部分的查找?

您能尝试一下是否可以解决? 生成列表需要很长时间,但是报告结果似乎很快。

给定列表:

import random
limit = 50 # to set the number of elements
c = 0
x = [0 for x in range(limit)]

for n in range(limit):
    c += random.randint(1,100)
    x[n] = c
print(x)

由于它是一个有序列表,因此可以使用for循环来检索值:

z = 1600 # reference for lookup

res = ()
for i, n in enumerate(x):
  if n > z:
    res = (i, n)
    break

print (res) # this is the index and value of the elements that match the condition to break
print(x[res[0]-1]) # this is the element just before

暂无
暂无

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

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