gpt4 book ai didi

python-2.7 - 为什么链式(区间)比较不能在 numpy 数组上工作?

转载 作者:太空宇宙 更新时间:2023-11-03 20:56:06 26 4
gpt4 key购买 nike

a < b < cchained expression在 Python 中,看起来它适用于定义了适当比较运算符的对象,但不适用于 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

打印:

True
True
True
False
True
True
True
False
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-187-277da7750148> in <module>()
4 for n in numlist:
5 print 0 < n < 3.5
----> 6 print 0 < numlist < 3.5

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

最佳答案

0 < numlist < 3.5

相当于:

(0 < numlist) and (numlist < 3.5)

除了 numlist 仅计算一次。

两个结果之间的隐式导致了错误

关于python-2.7 - 为什么链式(区间)比较不能在 numpy 数组上工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56019933/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com