python - 从列表中随机选择的值的最近邻居?
问题描述
我有一个列表,我在其中随机选择一个数字。我现在想选择列表中与我选择的数字最接近的整数。以下是我到目前为止的内容:
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]
推荐阅读
- python - 用于在括号 python 后删除空格的正则表达式
- java - Intellij 停止 JavaFX 拖放
- php - 除了 Laravel 中的 id 之外,来自不同列的多对多关系
- r - 识别组中缺失的观察结果
- javascript - 在面积图上绘制折线图
- java - GKE 上的 Google Cloud Run for Anthos 服务如何连接到不同组织的不同项目上的 Firestore?
- sql - 如果数据库中不存在记录,则插入一条记录,如果记录已在数据库中,则向用户显示一条消息
- mysql - Sqoop 无法将数据从 MYSQL 导入 HBASE
- javascript - 根据 Android Chrome 上的字体大小调整图像大小
- java - 我想通过使用 sqlite(数据)在 gridview 中查看数据,但我的应用程序变得太慢