在这里谈论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
长度也会变化
答案 0 :(得分:2)
当密钥是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
答案 1 :(得分:0)
您可以先对列表进行排序,然后使用二进制搜索:
<!DOCTYPE html>
<html>
<head>
<style>
.example {
width: 100%;
}
.span-full-height {
display: inline;
height: 100%;
float: left;
width: 70%;
border-right: 0.5px solid black;
padding: 10px;
}
.span-half-height {
display: inline-block;
height: 50%;
width: 25%;
border-bottom: 0.5px solid black;
padding: 3px;
}
.span-half-height-2 {
display: inline-block;
height: 50%;
width: 25%;
padding: 3px;
}
</style>
</head>
<body>
<div class="example">
<div class="span-full-height">
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p>
</div>
<div class="span-half-height">
<p>Hello World</p>
<p>How are you?</p>
</div>
<div class="span-half-height-2">
<p>Contact: 00000000</p>
</div>
</div>
</body>
</html>
您可以构建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)
此方法适用于 O(log n)用于舍入和 O(n log n)用于构建。因此,您将投入一些额外的时间来构建>>> 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
,但如果您经常调用它,它最终会在舍入个别数字时获得回报。