[英]Round Python list with unique values
我想“四舍五入”一個數字值的有序列表,可以是(正/負)浮點數或整數形式。 我不希望輸出中使用相同的值,除非輸入值本身相同。 理想情況下,我想四舍五入到最接近的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
任何幫助將不勝感激。
如果您保留一個四舍五入的數字字典(在round =鍵之前,在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和10。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.