具有唯一值的圆Python列表

2024-04-25 22:49:31 发布

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

我想“舍入”一个有序的数值列表,可以是(正/负)浮点数或整数的形式。我不希望输出中的值相同,除非传入值本身相同。理想情况下,我希望四舍五入到最接近的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

任何帮助都将不胜感激。你知道吗


Tags: 列表baselen情况整数abs形式int
1条回答
网友
1楼 · 发布于 2024-04-25 22:49:31

如果保留一个四舍五入的数字字典(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]

请随意将round函数更改为您自己的函数,以便仅将round合并为5和10。你知道吗

相关问题 更多 >