简体   繁体   English

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

[英]Combine 'if' statements into one comparison operator chain

Please help me in making one comparison operator chain out of the code below. 请帮助我从下面的代码中创建一个比较运算符链。 I am thinking in terms of 我在想

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

Here's the code to concise: 这是简明的代码:

if file <= 0:
    file = 0

if rank <= 0:
    rank = 0

if file => 7:
    file = 7

if rank => 7:
    rank = 7

how about 怎么样

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

min(file, 7) will return 7 at most; min(file, 7)最多返回7 max(x, 0) will return 0 or something bigger. max(x, 0)将返回0或更大的值。


you can only use chaining to check if something is within a range: 您只能使用链接来检查某项是否在范围内:

0 <= x <= 7

you cannot use chaining to check if something is outside a range: 您不能使用链接来检查是否超出范围:

0 <= x >= 7

will always be False (as it evaluates as (0 <= x) and (x >= 7) ). 将始终为False (因为其求值为(0 <= x) and (x >= 7) )。


if your variables are integers you could use: 如果变量是整数,则可以使用:

x not in range(0, 8)
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)

If you already happen to be using numpy , then it already has clip : https://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html 如果您恰好正在使用numpy ,那么它已经具有了以下cliphttps : //docs.scipy.org/doc/numpy/reference/generation/numpy.clip.html

Thanks for all your help, but what I ended up with is this: 感谢您的所有帮助,但最终我得到的是:

file = 0 if file < 0 else 7 if file > 7 else file
rank = 0 if rank < 0 else 7 if rank > 7 else rank

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM