python波浪号一元运算符作为否定numpy bool数组 [英] python tilde unary operator as negation numpy bool array
问题描述
应该是一个简单的问题,但我无法在任何地方找到答案.python 中的 ~
运算符被记录为按位反转运算符.美好的.不过,我注意到了看似精神分裂的行为,即:
Should be a simple question, but I'm unable to find an answer anywhere. The ~
operator in python is a documented as a bitwise inversion operator. Fine. I have noticed seemingly schizophrenic behavior though, to wit:
~True -> -2
~1 -> -2
~False -> -1
~0 -> -1
~numpy.array([True,False],dtype=int) -> array([-2,-1])
~numpy.array([True,False],dtype=bool) -> array([False,True])
在前 4 个示例中,我可以看到 python 正在实现(如文档所述)~x = -(x+1)
,输入被视为 int 即使它是布尔.因此,对于标量布尔值,~
不被视为逻辑否定.并不是说在使用 int 类型的布尔值定义的 numpy 数组上的行为是相同的.
In the first 4 examples, I can see that python is implementing (as documented) ~x = -(x+1)
, with the input treated as an int even if it's boolean. Hence, for a scalar boolean, ~
is not treated as a logical negation. Not that the behavior is identical on a numpy array defined with boolean values by with an int type.
为什么 ~
然后在布尔数组上用作逻辑否定运算符(另请注意:~numpy.isfinite(numpy.inf) -> True
?)?
Why does ~
then work as a logical negation operator on a boolean array (Also notice: ~numpy.isfinite(numpy.inf) -> True
?)?
我必须在标量上使用 not()
非常烦人,但是 not()
不能用于否定数组.那么对于一个数组,我必须使用 ~
,但是 ~
不能用来否定一个标量...
It is extremely annoying that I must use not()
on a scalar, but not()
won't work to negate an array. Then for an array, I must use ~
, but ~
won't work to negate a scalar...
推荐答案
not
是通过 __nonzero__
特殊方法实现的,需要返回 True
或 False
,因此无法给出所需的结果.而是使用了 ~
运算符,它通过 __not__
特殊方法实现.出于同样的原因,&
和 |
用于代替 and
和 or
.
not
is implemented through the __nonzero__
special method, which is required to return either True
or False
, so it can't give the required result. Instead the ~
operator is used, which is implemented through the __not__
special method. For the same reason, &
and |
are used in place of and
and or
.
PEP 335 旨在允许布尔运算符的重载,但由于开销过大而被拒绝(它例如会使 if
语句复杂化).PEP 225 建议了元素"运算符的通用语法,这将提供更通用的解决方案,但已延期.看来目前的情况虽然尴尬,但还不足以迫使改变.
PEP 335 aimed to allow overloading of boolean operators but was rejected because of excessive overhead (it would e.g. complicate if
statements). PEP 225 suggests a general syntax for "elementwise" operators, which would provide a more general solution, but has been deferred. It appears that the current situation, while awkward, is not painful enough to force change.
np.isfinite
在标量上调用时返回 np.bool_
类型的值,而不是 bool
.np.bool_
也是从 bool dtype 数组中提取标量值时获得的类型.如果您使用 np.True_
和 np.False_
代替 True
和 False
,您将在下获得一致的行为~
.
np.isfinite
when called on a scalar returns a value of type np.bool_
, not bool
. np.bool_
is also the type you get when extracting a scalar value from an array of bool dtype. If you use np.True_
and np.False_
in place of True
and False
you will get consistent behaviour under ~
.
这篇关于python波浪号一元运算符作为否定numpy bool数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!