简体   繁体   中英

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. 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.

You can use 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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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