将“ if”语句合并到一个比较运算符链中

时间:2019-06-18 09:52:57

标签: python python-3.x

请帮助我根据以下代码制作一个比较运算符链。我在考虑

if 0 <= file >= 7 or 0 <= rank >= 7:
    file = 0
    rank = 0

以下是要简化的代码:

if file <= 0:
    file = 0

if rank <= 0:
    rank = 0

if file => 7:
    file = 7

if rank => 7:
    rank = 7

3 个答案:

答案 0 :(得分:4)

怎么样

file = max(min(file, 7), 0)
rank = max(min(rank, 7), 0)

min(file, 7)最多返回7max(x, 0)将返回0或更大的值。


您只能使用链接来检查某项是否在范围内:

0 <= x <= 7

您不能使用链接来检查某物是否超出范围:

0 <= x >= 7

将始终为False(因为它的值为(0 <= x) and (x >= 7))。


如果您的变量是整数,则可以使用:

x not in range(0, 8)

答案 1 :(得分:1)

def clip(number: int, lower_bound: int, upper_bound: int) -> int:
    clipped_lower = max(lower_bound, number)
    clipped = min(clipped_lower, upper_bound)
    return clipped

lower_bound = 0
upper_bound = 7
file = clip(file, lower_bound, upper_bound)
rank = clip(rank, lower_bound, upper_bound)

如果您恰好正在使用numpy,则它已经具有cliphttps://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html

答案 2 :(得分:-1)

感谢您的所有帮助,但最后我得到的是:

if file < 0:
    file = 0
elif file > 7:
    file = 7

if rank < 0:
    rank = 0
elif rank > 7:
    rank = 7