获取特定值周围的值集

2024-04-20 02:03:14 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有x = 0.5的以下值

我怎样才能得到它周围的一组值:

y = [-4,-2 -5 , 0.5 , 1 , 3, 6,8]

有没有一个python函数可以做到这一点:

radomaround(value, numberOfValuesBefor,numberofvaluesafter) 

randomaround(value,numberofValues)


Tags: 函数valuenumberofvaluesnumberofvaluesafternumberofvaluesbeforradomaroundrandomaround
1条回答
网友
1楼 · 发布于 2024-04-20 02:03:14

对我来说,这似乎是一个非常特殊的情况,所以我想你需要给自己写一个:

import random

def randaround(value, low, hi, num=5):
    lower = [random.uniform(low, value) for _ in range(num)]
    higher = [random.uniform(value, hi) for _ in range(num)]
    return lower + [value] + higher
x = 0.5
print(randaround(x, -2, 4))

输出:

[0.33673180511496215, -1.2546042323682594, -0.681556151907607, 0.3568323009807952, -0.24707450425223398, 0.5, 1.0553226028673577, 2.913246921202094, 1.5029344184335343, 2.420987178172286, 1.8538880531275126]

如果您想对它们进行排序,当然可以在组装返回的列表之前对它们进行排序

相关问题 更多 >