使用Python 3,比起这样做,是否有更多的Pythonic方式可以使地板/天花板浮离零:
import math
def away_from_zero(x):
if x > 0:
return int(math.ceil(x))
else:
return int(math.floor(x))
是否有更好的(也许更优雅的)方法来获得具有更大绝对值的最近整数?
下面的行(ternary
运算符如何:]
return int(math.ceil(x)) if x > 0 else int(math.floor(x))
我不知道pythonic = short还是您不使用math
模块。无论哪种方式,这都是使用三元运算符和内置的round
函数同时满足的解决方案:
def away_from_zero(x):
return round(x + 1) if x > 0 else round(x - 1)