我想“舍入”一个有序的数值列表,可以采用(正/负)浮点数或整数形式。除非传入值本身相同,否则我不希望输出中包含相同的值。理想情况下,我希望舍入到最接近的5或10,以尽可能高的幅度执行,然后下降直到相邻值之间不匹配。
以下是我正在寻找的一些例子:
[-0.1, 0.21, 0.29, 4435.0, 9157, 9858.0, 10758.0, 11490.0, 12111.9]
结果:
[-0.1, 0.0, 0.25, 5000.0, 9000.0, 10000.0, 11000.0, 11500.0, 12000.0]
这是我到目前为止所拥有的:
def rounder(n, base=1):
base = base * (10 ** (len(str(abs(n))) - len(str(abs(n)))))
return base * round(float(n)/base)
for i in range(len(inp_values)-1):
while True:
a = rounder(inp_values[i], 10**((len(str(abs(int(inp_values[i])))))-(i+1)) / 2)
b = rounder(inp_values[i+1], 10**((len(str(abs(int(inp_values[i+1])))))-(i+1)) / 2)
print a, b
if a < b:
break
非常感谢任何帮助。
答案 0 :(得分:1)
如果你保留一个你舍入的数字字典(在round = key之前,在round = value之后),并且如果舍入的值会在字典中发生碰撞,那么写一个for循环使用较少的精度会怎么样?例如:
from math import log10, floor
def roundSD(x, sd):
"Returns x rounded to sd significant places."
return round(x, -int(floor(log10(abs(x)))) + sd - 1)
def round5(x, sd):
"Returns x rounded to sd significant places, ending in 5 and 0."
return round(x * 2, -int(floor(log10(abs(x)))) + sd - 1) / 2
inputData = [-0.1, 0.21, 0.29, 4435.0, 9157, 9858.0, 10758.0, 11490.0, 12111.9]
roundedDict = {}
roundedData = []
for input in inputData:
if input in roundedDict:
# The input is already calculated.
roundedData.append(roundedDict[input])
continue
# Now we attempt to round it
success = False
places = 1
while not success:
rounded = roundSD(input, places)
if rounded in roundedDict.values():
# The value already appeared! We use better precision
places += 1
else:
# We rounded to the correct precision!
roundedDict[input] = rounded
roundedData.append(rounded)
success = True
这将保证两个数字是否相同,它们将提供相同的舍入输出。如果两个数字不同,它们将永远不会给出相同的输出。
从上面开始运行:
[-0.1, 0.2, 0.3, 4000.0, 9000.0, 10000.0, 11000.0, 11500.0, 12000.0]
随意将圆形功能更改为您自己的圆形功能以将圆形功能合并到5&amp;只有10个。