在 python 中将字典中的值四舍五入到最接近的 5?

Round value in dictionary to nearest 5 in python?

我想将字典值中的一个元素四舍五入到最接近的 5。

给定一个字典:

d = {'0': '0 43 1000 27 3 I', '1': '2 52 1020 28 3 J', '2': '2 11 10 281 32 T'}

我想return每个dict的值中的第二个元素,并将其四舍五入到最接近的5。所以四舍五入到45,52到50和11到10。

到目前为止我只知道如何return字典中某个键的值,

for i in d['0']

但无法弄清楚其余部分。任何帮助将不胜感激。

要四舍五入到最接近的 5,您可以使用自定义函数:

def round_five(x):
    return 5 * round(x/5)

要访问您的 string 个号码中的第二个号码:

for k, v in d.items():
    # make a list out of the string
    nums = v.split(" ") 

    # round the 2nd element
    rounded = round_five(nums[1])

    # do something with the second element:
    print(rounded)

如果你不想在任何情况下使用 round 函数,通过破坏 round 函数本身的另一种方法是这样的:

def doit(d):
    for key, value in d.items():
    nums = value.split(" ")
    if int(nums[1])%5>=3:
        print((int(nums[1])//5)*5+5)
    else:
        print((int(nums[1])//5)*5)

谢谢。