从列表中选择单个浮动

2024-04-24 21:08:31 发布

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

我有一个浮动列表,从0到1按递增顺序生成。我需要对选定的浮点值执行一些操作,例如接近0.25、0.5、0.75的浮点值。但是生成的浮点可以有任意数量的小数位,并且可以重复,比如 ..........0.50001, 0.51125, 0.57466459, 0.5925, 0.5925, 0.634, .......... 你知道吗

我只需要从0.5附近选择一个(任何一个都可以),其他季度也一样。一个虚构的例子

list_of_floats = my_some_function()
 for i in list_of_floats:
     if i is near 0.5:
        do_something()

我试过了

list_of_floats = my_some_function()
done_once = False
 for i in list_of_floats:
     if 0.5 < i < 0.6 and done_once is False:
        do_something()
        done_once = True

这种方法适用于0.5,但我也需要为其他检查点(0.25、0.75等)执行。一定有更好的办法。请帮忙。你知道吗


Tags: ofinforifismyfunctionsome
3条回答

我不太清楚你想要什么,但听起来你在找^{}。例如,如果要查找数组中0.01到0.5之间的所有浮点值,可以使用:

list_of_floats = np.array([0.50001, 0.51125, 0.57466459, 0.5925, 0.5925, 0.634])

# note that atol is the tolerance within which you want to select your floats
>>> list_of_floats[np.isclose(0.5, list_of_floats, atol = 0.01)]
array([0.50001])

或者,由于您只需要一个,任何一个都可以,请选择第一个:

>>> list_of_floats[np.isclose(0.5, list_of_floats, atol = 0.01)][0]
0.50001

我将从检查点列表和“near”的一些阈值开始(如果每个检查点的“near”不同,则在顶层或与每个检查点配对)。您可以利用按相同顺序排序的数据和检查点,只考虑列表中的第一个检查点,并在命中时将其从列表中弹出:

checkpoints = [.25, .5. .75]
for i in list_of_floats:
    if abs(i - checkpoints[0]) < .1:
        do_something()
        checkpoints.pop(0)
    if not checkpoints:
        break

如果希望值最接近0.5,则类似于这样的操作可能会使您达到:

import numpy

floats = numpy.array([0.1, 0.3, 0.48, 0.51, 0.55, 0.72, 0.8])

higher = numpy.where(floats > 0.5)
rest = numpy.where(floats[higher] < 0.6)
possibilities = floats[higher][rest]
print(min(possibilities))
>>>0.51

相关问题 更多 >