<p>排序列表的另一种方法是使用NumPy数组并使用<code>np.sort()</code>进行排序。使用数组的优点是在计算y=f(x)这样的函数时进行矢量化操作。下面是绘制正态分布的示例:</p>
<p><strong>不使用排序数据</strong></p>
<pre><code>mu, sigma = 0, 0.1
x = np.random.normal(mu, sigma, 200)
f = 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (x - mu)**2 / (2 * sigma**2) )
plt.plot(x,f, '-bo', ms = 2)
</code></pre>
<p><strong>输出1</strong></p>
<p><a href="https://i.stack.imgur.com/rkLoD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rkLoD.png" alt="enter image description here"/></a></p>
<p><strong>使用np.sort()</strong>这允许在计算正态分布时直接使用排序数组<code>x</code>。</p>
<pre><code>mu, sigma = 0, 0.1
x = np.sort(np.random.normal(mu, sigma, 200))
# or use x = np.random.normal(mu, sigma, 200).sort()
f = 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (x - mu)**2 / (2 * sigma**2) )
plt.plot(x,f, '-bo', ms = 2)
</code></pre>
<p>或者,如果x和y数据都未排序,则可以使用<code>numpy.argsort</code>对它们进行后验排序</p>
<pre><code>mu, sigma = 0, 0.1
x = np.random.normal(mu, sigma, 200)
f = 1/(sigma * np.sqrt(2 * np.pi)) *np.exp( - (x - mu)**2 / (2 * sigma**2) )
plt.plot(np.sort(x), f[np.argsort(x)], '-bo', ms = 2)
</code></pre>
<p>在这两种情况下,输出都是</p>
<p><strong>输出2</strong></p>
<p><a href="https://i.stack.imgur.com/2QRwL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2QRwL.png" alt="enter image description here"/></a></p>