擅长:python、mysql、java
<p>您可以尝试使用<a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow noreferrer">^{<cd1>}</a>。下面是一个用法示例:</p>
<pre><code>>>> nwords = 10
>>> words = {1, 5, 3, 8, 6}
>>> import numpy
>>> numpy.bincount(list(s), minlength=nwords) # words present
array([0, 1, 0, 1, 0, 1, 1, 0, 1, 0])
>>> 1 - numpy.bincount(list(s), minlength=nwords) # words absent
array([1, 0, 1, 0, 1, 0, 0, 1, 0, 1])
</code></pre>
<p>不幸的是,这仍然涉及到对<code>s</code>元素的Python级迭代(在<code>list</code>调用中是隐式的)。我找不到比先将其转换为<code>list</code>更快的方法来让NumPy在这里解释集合。在</p>
<p>一些计时(使用Python 3.6、NumPy 1.13.1)显示,此解决方案速度更快,但并不令人难以置信:</p>
^{pr2}$