[英]How do I find the closest number in a list that is greater than my number?
I want to get the closest number (or the index of it) in a list that is greater than a given number.我想在列表中获取大于给定数字的最接近的数字(或它的索引)。 The list:
名单:
lst=[1,2,5]
My number:我的号码:
num=3
If I use: min(lst, key=lambda x:abs(x-num))
it will give 2
but I want it to give me 5
如果我使用:
min(lst, key=lambda x:abs(x-num))
它会给我2
但我希望它给我5
You need to consider numbers greater than num
:您需要考虑大于
num
的数字:
output, index = min((i, idx) for idx, i in enumerate(lst) if i>num)
You could write an actual loop to do it:您可以编写一个实际的循环来执行此操作:
closest_greater = None
for item in lst:
if item > num and (closest_greater is None or item < closest_greater):
closest_greater = item
gives closest_greater = 5
给出最接近的
closest_greater = 5
Alternatively, you could give the min()
function a generator expression that includes only elements that are greater than num
或者,您可以给
min()
function 一个生成器表达式,其中仅包含大于num
的元素
min(i for i in lst if i > num)
Would you like to use a binary sort?你想使用二进制排序吗? In my tests, this is slightly faster.
在我的测试中,这稍微快一些。
import time
from bisect import bisect
def timer(func):
def function_timer(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
print "The runtime took {} seconds to complete".format(round(time.time() - start, 2))
return function_timer
test_list = [1, 7, 5, 6, 3, 8]
k = 3
@timer
def t1():
for x in range(1000000):
test_list[bisect(test_list, k)]
@timer
def t2():
for x in range(1000000):
min((i, idx) for idx, i in enumerate(test_list) if i > k)
yields产量
The runtime took 0.22 seconds to complete
The runtime took 0.94 seconds to complete
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.