在这里谈论Python 3。
我希望将一个数字四舍五入为一组可以变化的给定值
假设value_set = [x, y, z],并且为了示例x, y, z = 1, 3.12, 4,我正在寻找一个函数,该函数将给定的浮点数舍入到最接近的数字
custom_round(0) --> 1
custom_round(2.7) --> 3.12
请注意,它应该足够通用,以便value_set长度也会有所不同
发布于 2017-02-27 19:56:59
当键是x-n的绝对值(x是列表中的每一项)时,您可以使用min函数来查找列表中的最小值。
value_set = [1, 3.12, 4]
def return_closest(n):
return min(value_set, key=lambda x:abs(x-n))
number_to_check = 3
print (return_closest(number_to_check))
>>> 3.12发布于 2017-02-27 20:01:30
您可以通过首先对列表进行排序,然后使用二进制搜索来完成此操作:
from bisect import bisect_left
class CustomRound:
def __init__(self,iterable):
self.data = sorted(iterable)
def __call__(self,x):
data = self.data
ndata = len(data)
idx = bisect_left(data,x)
if idx <= 0:
return data[0]
elif idx >= ndata:
return data[ndata-1]
x0 = data[idx-1]
x1 = data[idx]
if abs(x-x0) < abs(x-x1):
return x0
return x1然后,你可以像这样构造你的CustomRound:
values = [1,3.12,4]
custom_round = CustomRound(values)简单地叫它:
>>> custom_round(0)
1
>>> custom_round(0.5)
1
>>> custom_round(1.5)
1
>>> custom_round(2.5)
3.12
>>> custom_round(3.12)
3.12
>>> custom_round(3.9)
4
>>> custom_round(4.1)
4
>>> custom_round(4.99)
4这种方法适用于O(log )中的舍入和O( n ) 中的构造。因此,您将花费一些额外的时间来构建custom_round,但是如果您经常调用它,它最终将在舍入单个数字时获得回报。
https://stackoverflow.com/questions/42485098
复制相似问题