擅长:python、mysql、java
<p>您可以使用来自<code>itertools</code>模块的<code>chain</code>和<code>repeat</code>函数:</p>
<pre><code>>>> from itertools import repeat,chain
>>> a={1,3}
>>> list(chain.from_iterable((repeat(i,l.count(i)) for i in a)))
[1, 1, 1, 3]
</code></pre>
<p>注意:作为一种更有效的方法,您可以为<code>a</code>使用一个<code>set</code>容器,该容器对于成员身份检查具有O(1)复杂性,并且您不需要调用<code>list</code>如果您不需要结果作为列表,<code>chain.from_iterable</code>返回一个<a href="https://docs.python.org/2/library/stdtypes.html#iterator-types" rel="nofollow">iterator</a>。你知道吗</p>
<p>或者,作为一种非常优化的方法,您可以使用<code>numpy</code>,它在处理大量列表时特别强大:</p>
<pre><code>>>> import numpy as np
>>> l = np.array([1, 1 , 1, 2, 3, 4, 5, 5])
>>> a = (1, 3)
>>> l[np.in1d(l,a)]
array([1, 1, 1, 3])
</code></pre>