【问题标题】:and logical operation on python 2.7 [duplicate]和 python 2.7 上的逻辑操作 [重复]
【发布时间】:2017-11-24 10:27:25
【问题描述】:

我在 Ubuntu 16.04 上使用 python 2.7.12,我在代码的某些部分有这个:

for i in np.arange(0,max+1):
    ...
    if i != 1 and i != max :
            t_try[i] = (C_[i])/(2.0*D)

但是我得到了不同的结果:

for i in np.arange(0,max+1):
    ...
    if (i != 1) and (i != max) :
            t_try[i] = (C_[i])/(2.0*D)

for i in np.arange(0,max+1):
    ...
    if (i != 1 and i != max) :
            t_try[i] = (C_[i])/(2.0*D)

我没看出来是什么问题。

更新:请注意我不是在谈论“布尔运算符”和“按位运算符”接受的答案是 @fernand 的答案,顺便说一句,感谢您宝贵的时间

【问题讨论】:

  • 您能解释一下您尝试实现的目标以及预期的输出吗?您是否需要逻辑和 (and) 或按位 & (在您的情况下可能是相同的,因为您似乎在按位对布尔值进行操作......)?按位 & 的优先级高于 !=and,这意味着它首先应用 - 基于 mathcs.emory.edu/~valerie/courses/fall10/155/resources/…

标签: python python-2.7 bitwise-operators logical-operators


【解决方案1】:

这是为了运算符的优先级: https://docs.python.org/2/reference/expressions.html or, and 普遍存在于 ==, =!

【讨论】:

    【解决方案2】:

    python 中,& 不是逻辑连接,而是按位与运算符。尝试在您的示例中将 & 更改为 and

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多