a < b < c
是Python中的一个chained expression,它看起来像是在定义了适当的比较运算符的对象上工作,但它不适用于numpy数组。为什么?在
import numpy as np
class ContrarianContainer(object):
def __init__(self, x):
self.x = x
def __le__(self, y):
return not self.x <= y
def __lt__(self, y):
return not self.x < y
def __ge__(self, y):
return not self.x >= y
def __gt__(self, y):
return not self.x > y
def __eq__(self, y):
return not self.x == y
def __ne__(self, y):
return not self.x != y
numlist = np.array([1,2,3,4])
for n in numlist:
print 0 < n < 3.5
for n in numlist:
print 0 > ContrarianContainer(n) > 3.5
print 0 < numlist < 3.5
打印:
^{pr2}$
所以医生说:
以及
对于标量
但是用一个数组
^{pr2}$在需要标量布尔值的上下文中使用numpy布尔值时,会出现此值错误。在
它计算},但没有}。在
0<x
,但甚至不能计算x<10
,因为它不能在or/and
上下文中使用得到的布尔数组。numpy
定义了|
和{or
或{当我们使用
0 < x <10
时,我们隐含地期望计算标量链表达式的矢量化版本。在请注意,尝试对列表应用链接甚至不会超过第一个
<
:这组表达式表示
&
运算符优先于<
运算符:所以安全版本是}在{之前求值。在
(0 < x) & (x<10)
,确保所有{相当于:
^{pr2}$只是
numlist
只计算一次。在两个结果之间的隐式
and
导致了错误相关问题 更多 >
编程相关推荐