从整数列表中获取最接近给定值的数字 [英] from list of integers, get number closest to a given value

查看:250
本文介绍了从整数列表中获取最接近给定值的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个整数列表,我想找到哪个数字最接近我输入的数字:

Given a list of integers, I want to find which number is the closest to a number I give in input:

>>> myList = [4, 1, 88, 44, 3]
>>> myNumber = 5
>>> takeClosest(myList, myNumber)
...
4

有没有快速的方法吗?

推荐答案

如果我们不确定列表是否已排序,我们可以使用内置 min() function ,找到与指定数字的距离最小的元素。

If we are not sure that the list is sorted, we could use the built-in min() function, to find the element which has the minimum distance from the specified number.

>>> min(myList, key=lambda x:abs(x-myNumber))
4

请注意,它也适用于带有int键的dicts,例如 {1:a,2:b} 。此方法需要O(n)时间。

Note that it also works with dicts with int keys, like {1: "a", 2: "b"}. This method takes O(n) time.

如果列表已经排序,或者您可以支付排序价格只使用一次数组,使用 @ Lauritz的答案中所示的二分法,该方法仅需要O(log n)时间(但请注意检查列表是否已经排序是O(n)并且排序是O(n log n)。)

If the list is already sorted, or you could pay the price of sorting the array once only, use the bisection method illustrated in @Lauritz's answer which only takes O(log n) time (note however checking if a list is already sorted is O(n) and sorting is O(n log n).)

这篇关于从整数列表中获取最接近给定值的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆