myArr = array([4,1,88,44,3])
myNumber = 25
FindClosest(myArr, myNumber)
...
4, 44
有没有办法在列表中找到最接近的2个数字给某个数字,使其中一个更高而另一个更低?
我可以通过以下方式找到最接近的号码:
min(myArr.tolist(), key=lambda x:abs(x-myNumber))
答案 0 :(得分:14)
排序不是必需的,并且当它应该只是O(n)时,使这个时间复杂度为O(n logn)。
我相信这是你正在寻找的,利用numpy数组索引:
{{1}}
答案 1 :(得分:2)
first = min([for i in myArr if a>i])
second = max([for i in myArr if a<i])
此外,正确答案为44, 4
而非44, 88
答案 2 :(得分:1)
upper = min([ i for i in myArr.tolist() if i >= myNumber], key=lambda x:abs(x-myNumber))
lower = min([ i for i in myArr.tolist() if i < myNumber], key=lambda x:abs(x-myNumber))
答案 3 :(得分:1)
我有一个答案,找到输入值最接近的2个数字,请参阅下面的程序: -
from collections import OrderedDict
def find_closer():
a = [9, 19, 87, 43, 10]
b = int(input("Enter number :"))
# diff_list = []
diff_dict = OrderedDict()
if b in a:
b = input("Number already exists, please enter another number ")
else:
for x in a:
diff = x - b
if diff < 0:
# diff_list.append(diff*(-1))
diff_dict[x] = diff*(-1)
else:
# diff_list.append(diff)
diff_dict[x] = diff
print("diff_dict", diff_dict)
# print(diff_dict[9])
sort_dict_keys = sorted(diff_dict.keys())
print(sort_dict_keys)
closer_less = 0
closer_more = 0
for closer in sort_dict_keys:
if closer < b:
closer_less = closer
else:
closer_more = closer
break
print("closer less =", closer_less, "and closer more =", closer_more)
find_closer()
这是一个纯粹的python程序。希望它有所帮助!!