Python中的地板或天花板距离零的位置

问题描述 投票:0回答:2

使用Python 3,比起这样做,是否有更多的Pythonic方式可以使地板/天花板浮离零:

import math

def away_from_zero(x):
    if x > 0:
        return int(math.ceil(x))
    else:
        return int(math.floor(x))

是否有更好的(也许更优雅的)方法来获得具有更大绝对值的最近整数?

python-3.x rounding floor ceil
2个回答
0
投票

下面的行(ternary运算符如何:]

return int(math.ceil(x)) if x > 0 else int(math.floor(x))

0
投票

我不知道pythonic = short还是您不使用math模块。无论哪种方式,这都是使用三元运算符和内置的round函数同时满足的解决方案:

def away_from_zero(x):
    return round(x + 1) if x > 0 else round(x - 1)
© www.soinside.com 2019 - 2024. All rights reserved.