简体   繁体   English

从列表中随机选择的值的最近邻居?

[英]Closest neighbor to value selected at random from list?

I have a list where I am selecting a number at random.我有一个列表,我在其中随机选择一个数字。 I now want to choose the closest integer in the list to the number I have selected.我现在想在列表中选择与我选择的数字最接近的 integer。 Below is what i have so far:以下是我到目前为止的内容:

from random import choice

a = [0,1,2,3,4,5,6,7,8,9]
r = choice(a)

So for example if r = 9, the nearest neighbor would be 8. For r=7 it could be either 6 or 8. Which of the two closest isn't particularly important, so long as it is a neighboring value.因此,例如,如果 r = 9,则最近的邻居将是 8。对于 r=7,它可能是 6 或 8。两个最接近的不是特别重要,只要它是相邻值即可。

You can use numpy您可以使用 numpy

from random import choice
import numpy as np

a = np.array([0,1,2,3,4,5,6,7,8,9])
r = choice(a)

neighs = a[abs(a - r) == 1]

print(r, neighs)
# 7 , [6 8]

You can also use this method that sorts the array and searches for the closest neighbour.您还可以使用此方法对数组进行排序并搜索最近的邻居。 As you mention that the choice between the two closest isn't particularly important, so long as it is a neighbouring value ie for r=7 it could be either 6 or 8. This method chooses the smallest of the two closest neighbour ie for r=7 it selects 6 not 8.正如您提到的,两个最接近的邻居之间的选择并不是特别重要,只要它是相邻值,即 r=7,它可以是 6 或 8。此方法选择两个最接近的邻居中的最小者,即 r =7 它选择 6 而不是 8。

def getclosest(targetVal, sample):
    dif=100; cand=0;
    for x in sample:
        if (abs(x - targetVal) < dif)& (x!=targetVal):
            dif = abs(x - targetVal);
            cand = x;
    return cand;

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

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