脾气暴躁:需要一臂之力才能理解"in"操作会发生什么情况.操作员 [英] Numpy: need a hand in understanding what happens with the "in" operator

查看:81
本文介绍了脾气暴躁:需要一臂之力才能理解"in"操作会发生什么情况.操作员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人可以帮助我(并解释发生的事情),我将不胜感激.

I would appreciate if somebody could help me with this (and explaining what's going on).

这有效:

>>> from numpy import array
>>> a = array((2, 1))
>>> b = array((3, 3))
>>> l = [a, b]
>>> a in l
True

但这不是:

>>> c = array((2, 1))
>>> c in l
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

我要复制的行为是:

>>> x = (2, 1)
>>> y = (3, 3)
>>> l2 = [x, y]
>>> z = (2, 1)
>>> z in l2
True

请注意,以上内容也适用于可变对象:

Note that what above also work with mutable objects:

>>> x = [2, 1]
>>> y = [3, 3]
>>> l2 = [x, y]
>>> z = [2, 1]
>>> z in l2
True

当然知道:

>>> (a < b).all()
True

我尝试了(但失败了):

I tried (and failed):

>>> (c in l).all()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

推荐答案

Python选择bool([False,True])True是因为(它说)任何非空列表的布尔值均为True.

Python makes the choice that bool([False,True]) is True because (it says) any non-empy list has boolean value True.

Numpy选择bool(np.array([False, True]))应该引发ValueError.从一些角度设计Numpy的目的是,某些用户可能想知道数组中的任何个元素是否为True,而其他用户可能想知道 all 个元素是否在数组中为True.由于用户的愿望可能有冲突,因此NumPy拒绝猜测.它会引发ValueError并建议使用np.anynp.all(尽管如果希望复制类似Python的行为,则可以使用len).

Numpy makes the choice that bool(np.array([False, True])) should raise a ValueError. Numpy was designed from the point of view that some users may want to know if any of the elements in the array are True, while others may want to know if all the elements in the array are True. Since the users may have conflicting desires, NumPy refuses to guess. It raises a ValueError and suggests using np.any or np.all (though if one wishes to replicate Python-like behavior, you'd use len).

当您评估c in l时,Python会将cl中的每个元素(从a开始)进行比较.评估bool(c==a).我们得到bool(np.array([True True])),它会引发ValueError(由于上述原因).

When you evaluate c in l, Python compares c with each element in l starting with a. It evaluates bool(c==a). We get bool(np.array([True True])), which raises a ValueError (for the reason described above).

由于numpy拒绝猜测,因此您必须明确.我建议:

Since numpy refuses to guess, you have to be specific. I suggest:

import numpy as np
a=np.array((2,1))
b=np.array((3,3))
c=np.array((2,1))
l=[a,b]
print(any(np.all(c==elt) for elt in l))
# True

这篇关于脾气暴躁:需要一臂之力才能理解"in"操作会发生什么情况.操作员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆