gpt4 book ai didi

python - 同时舍入列表中的单独值

转载 作者:行者123 更新时间:2023-12-01 06:02:26 25 4
gpt4 key购买 nike

我想写一些看起来有点像我目前在以下定义中的内容:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com