从整数列表中获取最接近给定值的数字
给定一个整数列表,我想找到哪个数字最接近我输入的数字:
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).)