首页 文章

PyCharm:“简化链式比较”

提问于
浏览
159

我有一个整数值 x ,我需要检查它是否在 startend 之间,所以我写下面的语句:

if x >= start and x <= end:
    # do stuff

这个陈述有下划线,工具提示告诉我必须

简化链式比较

据我所知,这种比较就像它们来的一样简单 . 我错过了什么?

3 回答

  • -1

    它可以改写为:

    start <= x <= end:
    

    要么:

    r = range(start, end + 1) # (!) if integers
    if x in r:
        ....
    
  • 278

    简化代码

    if start <= x <= end: # start x is between start and end 
    # do stuff
    
  • 8

    在Python中,您可以"chain" comparison operations,这意味着它们一起被"and"编辑 . 在你的情况下,它是这样的:

    if start <= x <= end:
    

    参考:https://docs.python.org/3/reference/expressions.html#comparisons

相关问题