【问题标题】:In python, what is the meaning of a<b<c?在python中,a<b<c是什么意思?
【发布时间】:2020-02-09 20:22:48
【问题描述】:

if a[start] &lt;= target &lt; a[mid]a[start] &lt;= target and target&lt;a[mid] and a[start] &lt; a[mid] 一样吗? (我认为不是,但在视觉上看起来两者是相同的)这在引擎盖下是如何工作的?在 SO 上搜索,但找不到答案。

【问题讨论】:

    标签: python boolean comparison operators comparison-operators


    【解决方案1】:

    if a[start] <= target < a[mid]:
    

    本质上[*]与

    相同
    if a[start] <= target and target < a[mid]:
    

    (如果为真,则a[start] &lt; a[mid],因为&lt;= 应该是可传递的。)

    [*] 有一个微妙之处不适用于您的案例,但值得了解。链式形式只计算一次中间表达式,而扩展形式计算两次。如果中间表达式的计算成本很高或有一些副作用(例如在屏幕上打印某些内容),这可能很重要。

    相关文档:https://docs.python.org/3/reference/expressions.html#comparisons

    【讨论】:

    • 哦,有趣!你能给我一个例子吗,只使用a[start] &lt;= target and target &lt; a[mid] 将评估为假的数字
    • @Satya 你可以像这样使用三元运算符:a = True if a[start]
    猜你喜欢
    • 1970-01-01
    • 2014-02-09
    • 2012-06-14
    • 1970-01-01
    • 2010-12-31
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    相关资源
    最近更新 更多