简体   繁体   English

以给定精度舍入 Python 中由浮点数表示的字典键的最佳方法

[英]Best way to round a Dictionary key represented by a float in Python with a given precision

I have a list of lists like我有一个清单清单

firstlist = [[x1,12.0,text,0.05],[x2,12.0,text,0.08],[x3,14.0,text,0.05],[x4,16.0,text,0.05],[x5,12.0,text,0.08]]

I tried to create a dictionary like我试图创建一个像这样的字典

mydict = {0.05:[[x1,12.0,text,0.05],[x3,14.0,text,0.05],[x4,16.0,text,0.05]],
          0.08:[[x2,12.0,text,0.08],[x5,12.0,text,0.08]]}


d = {}
for row in FirstList[1:]:
    # Add name to dict if not exists
    if len(row)==13:
        if row[12] not in d:
            d[row[12]] = []
            # Add all non-Name attributes as a new list
        d[row[12]].append(row[1:])

where keys represent commissions.其中键代表佣金。

My problem is that some commissions are very close resulting more rows.我的问题是一些佣金非常接近导致更多行。

for example例如

 mydict = {0.05:[[x1,12.0,text,0.05],[x3,14.0,text,0.05],[x4,16.0,text,0.05]],
           0.048:[[x2,12.0,text,0.048],[x5,12.0,text,0.048]],
           0.051:[[x2,12.0,text,0.051],[x5,12.0,text,0.051]]}

how to have the keys for example if keys are 0.049 or 0.051 with a difference of 0.01-0.02 and close to 0.050 to be 0.05如何获得密钥,例如,如果密钥为 0.049 或 0.051,差异为 0.01-0.02,接近 0.050 为 0.05

You are using the value at index 12 as key for the dictionary.您正在使用索引12处的值作为字典的键。 You can round the value before passing it as the key.您可以在将值作为键传递之前对其进行舍入。

d = {}
for row in FirstList[1:]:
    # Add name to dict if not exists
    if len(row)==13:
        key = round(row[12], 2)
        if key not in d:
            d[row[12]] = []
            # Add all non-Name attributes as a new list
        d[key].append(row[1:])

To handle the segmentation you posted in the comments, with keys on event numbers in the thousandths decimal place, you need to do some math to generate the key.要处理您在评论中发布的分段,事件编号的键位于小数点后千位,您需要进行一些数学计算以生成键。

Essentially, you have 5 bins between each hundredth decimal place to you need to round the values into.本质上,您需要将值四舍五入到每个小数点后的每一位之间有 5 个 bin。 We can accomplish this by multiplying by 5, rounding, dividing by 5, and rounding again (to clip the value).我们可以通过乘以 5、四舍五入、除以 5 并再次四舍五入(以裁剪值)来完成此操作。

def nearest_even_1000th(x):
    return round(round(x * 5, 2) / 5, 3)

d = {}
for row in FirstList[1:]:
    # Add name to dict if not exists
    if len(row)==13:
        key = nearest_even_1000th(row[12])
        if key not in d:
            d[row[12]] = []
            # Add all non-Name attributes as a new list
        d[key].append(row[1:])

You need the builtin function round你需要内置的 function round

round(0.05, 2)  # 0.05
round(0.048, 2) # 0.05
round(0.051, 2) # 0.05

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM