Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将字典中的值舍入到最接近的5?_Python_Python 3.x_Dictionary_Rounding - Fatal编程技术网

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

在python中将字典中的值舍入到最接近的5?,python,python-3.x,dictionary,rounding,Python,Python 3.x,Dictionary,Rounding,我想将字典值中的一个元素四舍五入到最接近的5 给一本字典: d = {'0': '0 43 1000 27 3 I', '1': '2 52 1020 28 3 J', '2': '2 11 10 281 32 T'} 我想返回每个dict值中的第二个元素,并将其四舍五入到最接近的5。所以第43轮对第45轮,第52轮对第50轮,第11轮对第10轮 到目前为止,我只知道如何返回dict中键的值 for i in d['0'] 但我想不出剩下的是什么。非常感谢您的帮助。若要四舍五入到最接近的5,

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

给一本字典:

d = {'0': '0 43 1000 27 3 I', '1': '2 52 1020 28 3 J', '2': '2 11 10 281 32 T'}
我想返回每个dict值中的第二个元素,并将其四舍五入到最接近的5。所以第43轮对第45轮,第52轮对第50轮,第11轮对第10轮

到目前为止,我只知道如何返回dict中键的值

for i in d['0']

但我想不出剩下的是什么。非常感谢您的帮助。

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

def round_five(x):
    return 5 * round(x/5)
要访问数字串中的第二个数字:

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)

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

def round_five(x):
    return 5 * round(x/5)
要访问数字串中的第二个数字:

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)

谢谢。

如果您在任何情况下都不想使用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)

谢谢。

您不需要11点到10点吗?您是否也可以发布预期的输出?您是否需要11到10?你能发布一个预期的结果吗?愿上天保佑你的灵魂。谢谢你,愿上天保佑你的灵魂。非常感谢。