擅长:python、mysql、java
<p>这个答案类似于<a href="https://stackoverflow.com/questions/16118621/first-common-element-from-two-lists">a similar question</a>上的<a href="https://stackoverflow.com/questions/16118621/first-common-element-from-two-lists/16118989#16118989">an answer</a>,其中@jamylak与其他算法相比更详细地说明了结果的计时。在</p>
<p>如果只需要匹配的第一个元素,请使用<a href="https://docs.python.org/2/library/functions.html#next" rel="nofollow"><strong>^{<cd1>}</strong></a>:</p>
<pre><code>>>> a = [1, 2, 3, 4, 5]
>>> b = [14, 17, 9, 3, 8]
>>> next(element for element in a if element in b)
3
</code></pre>
<p>这不是很有效,因为它对每个元素执行<code>b</code>的线性搜索。您可以从<code>b</code>创建一个<code>set</code>,它具有更好的查找性能:</p>
^{pr2}$
<p>如果<code>next</code>找不到任何内容,则会引发异常:</p>
<pre><code>>>> a = [4, 5]
>>> next(element for element in a if element in b_set)
Traceback (most recent call last):
StopIteration
</code></pre>
<p>您可以给它一个默认的返回值,例如<code>None</code>。但是,这会改变函数参数解析的语法,您必须显式创建生成器表达式:</p>
<pre><code>>>> None is next((element for element in a if element in b_set), None)
True
</code></pre>