擅长:python、mysql、java
<p>使用<code>list.index</code>的解决方案:</p>
<pre><code>def indices(lst, element):
result = []
offset = -1
while True:
try:
offset = lst.index(element, offset+1)
except ValueError:
return result
result.append(offset)
</code></pre>
<p>对于大型列表,它比使用<code>enumerate</code>进行列表理解快得多。如果</em>已经有了数组,它也比<code>numpy</code>解决方案<em>慢得多,否则转换的成本超过了速度增益(在包含100、1000和10000个元素的整数列表上测试)。</p>
<p><strong>注意:</strong>基于Chris_Rands评论的注意事项:如果结果足够稀疏,则此解决方案比列表理解快,但如果列表中有正在搜索的元素的多个实例(在1000个整数的列表中,超过列表的约15%),则列表理解快。</p>