擅长:python、mysql、java
<p>使用<a href="https://thispointer.com/numpy-where-tutorial-examples-python/" rel="nofollow noreferrer">np.where</a></p>
<pre><code>def bound_where(array):
return np.where(array==0, 0, np.where(array<0, MIN, 1)), \
np.where(array==0, 0, np.where(array<0, -1, MAX))
</code></pre>
<p>与其他方法的比较</p>
<p><strong>测试</strong></p>
<p>方法</p>
<ol>
<li>张贴方法</li>
<li>选择方法(来自@QuangHoang answer的边界2)</li>
<li>Where方法(当前答案)</li>
</ol>
<p><em>测试代码</em></p>
<pre><code>arr = np.random.randint(-10,10,1000)
count = 1000
print(f'Posted method: {timeit(lambda:bound(arr), number=count):.4f}')
print(f'Select method: {timeit(lambda:bound2(arr), number=count):.4f}')
print(f'Where mehtod: {timeit(lambda:bound_where(arr), number=count):.4f}')
</code></pre>
<p><strong>结果(秒)</strong></p>
<pre><code>Posted method: 6.1951
Select method: 0.3959
Where method: 0.1466
</code></pre>
<p>方法最快的地方在哪里</p>