import numpy as npmainList = []numpyArray0 = np.array([1,2,3])numpyArray1 = np.array([4,5,6])mainList.append(numpyArray0)mainList.append(numpyArray1)print("numpyArray0 in mainList:")try: print(numpyArray0 in mainList)except ValueError: print("ValueError")print("numpyArray1 in mainList:")try: print(numpyArray1 in mainList)except ValueError: print("ValueError")print("mainList in numpyArray0:")try: print(mainList in numpyArray0)except ValueError: print("ValueError")print("mainList in numpyArray1:")try: print(mainList in numpyArray1)except ValueError: print("ValueError")print(numpyArray1 in mainList)所以我上面的代码基本上是在一个普通的python列表(mainList)内创建2个numpy数组,然后检查这些2个数组是否在列表内。代码应该输出:numpyArray0 in mainList:TruenumpyArray1 in mainList:**True**mainList in numpyArray0:TruemainList in numpyArray1:True**True**但不是输出上述内容,而是输出以下内容:numpyArray0 in mainList:TruenumpyArray1 in mainList:ValueErrormainList in numpyArray0:TruemainList in numpyArray1:TrueTraceback (most recent call last): File "/home/user/Documents/pythonCode/temp.py", line 31, in <module> print(numpyArray1 in mainList)ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()我做错了什么吗?请注意,我在运行代码之前尝试更新 python、numpy 和我的操作系统(debian)。
3 回答
繁星淼淼
TA贡献1775条经验 获得超11个赞
numpyArray0 in mainList
调用list.__contains__
。列表的__contains__
方法调用列表的PyObject_RichCompareBool
每个元素来检查元素是否相等。碰巧的是,首先PyObject_RichCompareBool
检查身份相等性,然后进行全面比较。
numpyArray0 is mainList[0]
返回True
,因此永远不会进行完全比较。如果完成了完全比较,numpy
则会引发,ValueError
因为numpy
数组不能被解释为布尔值。
numpyArray1 in mainList
也显示了这一点(因为numpyArray1
vs 的身份比较失败了mainList[0]
。
宝慕林4294392
TA贡献2021条经验 获得超8个赞
这里的要点:
>>> numpyArray1 in mainList
....
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
这将工作:
>>> any([list(numpyArray1) == list(litem) for litem in mainList])
True
添加回答
举报
0/150
提交
取消