我想将字典值中的元素四舍五入到最接近的5。
给定字典:
d = {'0': '0 43 1000 27 3 I', '1': '2 52 1020 28 3 J', '2': '2 11 10 281 32 T'}
我想返回每个字典的值中的第二个元素,并将其四舍五入到最接近的5。因此,将43舍入为45,将52舍入为50,将11舍入为10。
到目前为止,我只知道如何在字典中返回键的值,
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句