gpt4 book ai didi

python-2.7 - 为什么链式(间隔)比较不适用于 numpy 数组?

转载 作者:行者123 更新时间:2023-12-03 16:41:09 24 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只评估一次。

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

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

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