<p><a href="https://docs.python.org/3/reference/expressions.html#value-comparisons" rel="nofollow">https://docs.python.org/3/reference/expressions.html#value-comparisons</a>描述值比较,如<code>==</code>。虽然默认比较是<code>identity</code><code>x is y</code>,但它首先检查任一参数是否实现了<code>__eq__</code>方法。数字、列表和字典实现它们自己的版本。<code>numpy</code>也是如此。你知道吗</p>
<p>关于<code>numpy</code><code>__eq__</code>的独特之处在于,如果可能的话,它会逐个元素进行比较,并返回相同大小的布尔数组。你知道吗</p>
<pre><code>In [426]: [1,2,3]==[1,2,3]
Out[426]: True
In [427]: z1=np.array([1,2,3]); z2=np.array([1,2,3])
In [428]: z1==z2
Out[428]: array([ True, True, True], dtype=bool)
In [432]: z1=np.array([1,2,3]); z2=np.array([1,2,4])
In [433]: z1==z2
Out[433]: array([ True, True, False], dtype=bool)
In [434]: (z1==z2).astype(float) # change bool to float
Out[434]: array([ 1., 1., 0.])
</code></pre>
<p>一个常见的SO问题是“为什么我会得到这个ValueError?”你知道吗</p>
<pre><code>In [435]: if z1==z2: print('yes')
...
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
</code></pre>
<p>这是因为比较生成的数组有多个真/假值。你知道吗</p>
<p>比较浮动也是一个常见的问题。检查一下<code>isclose</code>和<code>allclose</code>这个问题出现了。你知道吗</p>