首页 > 解决方案 > 从列表中随机选择的值的最近邻居?

问题描述

我有一个列表,我在其中随机选择一个数字。我现在想选择列表中与我选择的数字最接近的整数。以下是我到目前为止的内容:

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。两个最接近的不是特别重要,只要它是相邻值即可。

标签: pythonlistrandomlist-comprehension

解决方案


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

推荐阅读