【问题标题】:Logical OR without using numpy.logical_or不使用 numpy.logical_or 的逻辑或
【发布时间】:2015-03-06 14:19:46
【问题描述】:

要知道验证两个条件的numpy数组的元素,可以使用运算符*

>>> a = np.array([[1,10,2],[2,-6,8]])
>>> a
array([[ 1, 10,  7],
       [ 2, -6,  8]])
>>> (a <= 6) * (a%2 == 0) # elements that are even AND inferior or equal to 6
array([[False, False, False],
       [ True,  True, False]], dtype=bool)

但是 OR 呢?我试着这样做:

>>> (a%2 == 0) + (a <= 6) - (a%2 == 0) * (a <= 6)
array([[ True,  True, False],
       [False, False,  True]], dtype=bool)

但是验证这两个条件的元素的结果是错误的。我不明白为什么。

【问题讨论】:

  • 我没有看到 OR 运算符。
  • 对 numpy 布尔值的算术运算很俗气,依赖它们并不是最好的主意。此外,它们使您的代码晦涩难懂且难以解释。如果处理布尔数组,请使用位运算符:&amp; for and,| for or,^ for xor and ~ for not。
  • 如果一个答案解决了您的问题,请接受它作为解决方案,如here

标签: python arrays numpy logical-operators


【解决方案1】:

你不需要减法。 关键是+ 的行为已经像or 运算符

>>(a%2==0)+(a<=6)
array([[ True,  True,  True],
       [ True,  True,  True]], dtype=bool)

因为“True+True=True”。

当您减去(a&lt;=6)*(a%2==0) 时,您会将同时满足这两个条件的所有元素转换为false

做起来最简单

>>(a<=6)|(a%2==0)
array([[ True,  True,  True],
       [ True,  True,  True]], dtype=bool)

【讨论】:

  • 我的意见,但| 应始终优先于+。当我看到+ 时,我开始想知道为什么我们要把东西加在一起,或者事实上我们是在连接东西。一看到|,我就想到了与logical_or密切相关的bitwise_or。
【解决方案2】:

@plonser 的答案是正确的:使用+

如果你想再次使用乘法,你可以记住德摩根的一条定律告诉你

A or B

逻辑上等价于

not ( not A and not B )

所以在 NumPy 中你可以写:

>>> ~(~(a%2 == 0) * ~(a <= 6))
array([[ True,  True,  True],
       [ True,  True,  True]], dtype=bool)

但这不是特别可读。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-23
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 2021-11-29
    • 2019-12-08
    相关资源
    最近更新 更多