开发者社区> 问答> 正文

Python如何将字典值中的特定元素进行四舍五入

我想将字典值中的元素进行四舍五入

给定字典:

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

我想返回每个字典的值中的第二个元素,并将其四舍五入,例如将43舍入为45,将52舍入为50,将11舍入为10。

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

for i in d['0']

其他的应该怎么做呢?谢谢~

展开
收起
安忆333 2019-12-05 20:03:17 2357 0
1 条回答
写回答
取消 提交回答
  • 要进行四舍五入,可以自定义函数:

    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)
    
    2019-12-05 20:04:34
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载