【问题标题】:Understanding the OR operator [duplicate]了解 OR 运算符 [重复]
【发布时间】:2019-12-31 22:45:57
【问题描述】:

刚开始在 IDLE 中学习 Python,偶然发现:

numArray = [1, 2, 3, 1]
(1 or 7) in numArray #returns True
(7 or 1) in numArray #returns False

为什么(7 或 1)返回 False?

【问题讨论】:

  • 当你看到这个时,你应该已经在 Python 中运行了7 or 1。看到返回值为 7,您应该已经搜索了 python or operator。然后你就会明白为什么输出是这样的。

标签: python


【解决方案1】:

这是因为or 是从左到右评估的,以确保真实性。 1 和 7 都不是零,所以它们是“真实的”。

您是在告诉 Python 使用您的逻辑执行以下操作。

1 或 7 不是零吗?

Python 停在1。 1 是真实的。所以无论在() 解析为1。 1 也在您的列表中。

7 或 1 不是零吗?

Python 停在7,7 是真的。无论是在 () 解析为 7。 7 不在您的列表中。

【讨论】:

    【解决方案2】:
    numArray = [1, 2, 3, 1]
    

    现在让我们看看操作:

    (1 or 7) = 1 
    # The or operator stops evaluating when it finds an operand True. In this case, it stops at 1
    

    1 在数组中,这就是为什么True

    (7 or 1) = 7
    # The or operator stops when it finds an operand True. In this case, it stops at 7
    

    7 不在数组中,这就是为什么False

    当你这样做时:

    (0 or 7) 
    # The result would be `7` as the first operand is `0` and considered as `false` and hence the second operand is evaluated.
    

    但是,and 运算符在从左到右找到操作数“False”时停止计算,否则,计算直到最后一个。

    (1 and 7) = 7
    # Evaluates till the end since it did not find False and results in 7
    
    (7 and 1) = 7
    # Evaluates till the end since it did not find False and results in 1
    
    (0 and 5) = 0
    # The first operand is False and it stops here and results in 0
    

    【讨论】:

      【解决方案3】:

      or 操作返回两个值之间的第一个 True 操作数。如果所有操作数都是False,则返回最后一个操作数。示例:

      >>> 7 or 1
      7
      >>> bool(7)
      True
      >>> 
      >>> False or 0
      0
      >>> bool(0)
      False
      >>> 
      

      所以它看到7不在列表中并返回False

      如果您在 Python 中使用 or 测试两个对象,则运算符将返回第一个计算结果为 true 的对象或表达式中的最后一个对象,无论其真值如何 - @987654321 @

      【讨论】:

      • 声明Using or between two values returns the first value不正确。
      • @blhsing 进行了编辑
      • 编辑的语句更好,但应该说or运算符返回它从左到右计算的第一个truthy操作数,如果两者都不是truthy,则返回最后一个操作数。
      • @blhsing 也根据它编辑了代码
      【解决方案4】:

      您的意图类似于7 in numArray or 1 in numArray,但or 不会这样考虑。 7 or 1 首先被计算,然后 result 被用作in 的第一个操作数。由于7 or 1 的计算结果为7,因此您正在测试7 in numArray 是否为真。

      您似乎想改用any 函数。

      any(x in numArray for x in [1, 7])  # True
      any(x in numArray for x in [7, 1])  # Also True
      

      两者的区别是第一个会更快返回;一旦它发现1 in numArray 为真,它就会立即返回,而无需再检查任何值。第二个发现 7 不在 numArray 中,然后转到下一个值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-03-20
        • 1970-01-01
        • 2019-10-11
        • 2016-03-19
        • 1970-01-01
        • 1970-01-01
        • 2018-07-22
        相关资源
        最近更新 更多