作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想写一些看起来有点像我目前在以下定义中的内容:
def rounding( sp1, sp2, sp3, sp4 ):
if () <= 700.:
round(object, -1)
elif () <= 1000.:
round(object, (-1*5))
elif () <= 10000.:
round(object, -2)
elif () > 10000.:
round(object, -3)
else:
print "Error"
return [ sp1, sp2, sp3, sp4 ]
我确实是这一切的初学者,并且我可能在上面的代码中犯了一些可怕的错误。我基本上拥有的是之前计算的这 4 个值 sp1、sp2 等。然后我希望能够同时对这些值进行舍入,但根据它们各自的值,它们必须按不同的量舍入。
If 'sp' <= 700 : rounded to nearest 10
700 < sp <= 1000 : rounded to nearest 50
1000 < sp <= 10000 : rounded to nearest 100
10000 < sp : rounded to nearest 1000. (not code)
如果有什么可以帮助我,我将不胜感激,谢谢!
最佳答案
棘手的部分是舍入到最接近的 50。这可以通过将数字加倍,然后舍入到最接近的 100,然后再次将数字减半来实现。至少这是我能想到的最简单的方法。
def nearest_50(n):
return round(n*2, -2)/2
至于其余的,您的代码距离正确的解决方案并不遥远。正如 Ignacio 建议的那样,一次应该只舍入一个值
def my_round(n):
if n <= 700:
return round(n, -1)
elif n <= 1000:
return nearest_50(n)
elif n <= 10000:
return round(n, -2)
else:
return round(n, -3)
然后像这样对数字列表进行舍入
mylist = [... some numbers ...]
rounded = [my_round(n) for n in mylist]
关于python - 同时舍入列表中的单独值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9630649/
我是一名优秀的程序员,十分优秀!