簡體   English   中英

從列表中隨機選擇的值的最近鄰居?

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

我有一個列表,我在其中隨機選擇一個數字。 我現在想在列表中選擇與我選擇的數字最接近的 integer。 以下是我到目前為止的內容:

from random import choice

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

因此,例如,如果 r = 9,則最近的鄰居將是 8。對於 r=7,它可能是 6 或 8。兩個最接近的不是特別重要,只要它是相鄰值即可。

您可以使用 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]

您還可以使用此方法對數組進行排序並搜索最近的鄰居。 正如您提到的,兩個最接近的鄰居之間的選擇並不是特別重要,只要它是相鄰值,即 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