<p>你可以直接在<code>list-comprehension</code>-</p>
<pre><code>[element for element in list1 if bool(re.search(regexp, element))]
</code></pre>
<p>仔细观察,使用搜索方法,我们得到一个匹配的对象:</p>
<pre><code>In [175]: re.search(regexp, list1[0])
Out[175]: <_sre.SRE_Match at 0x7fc30bac1c60>
</code></pre>
<p>对于不匹配的情况,我们得到<code>None</code>。你知道吗</p>
<p>根据<a href="https://docs.python.org/3/reference/expressions.html#booleans" rel="nofollow noreferrer">^{<cd3>}</a>:</p>
<blockquote>
<p>In the context of Boolean operations, and also when expressions are
used by control flow statements, the following values are interpreted
as false: False, None, numeric zero of all types, and empty strings
and containers (including strings, tuples, lists, dictionaries, sets
and frozensets). All other values are interpreted as true.
User-defined objects can customize their truth value by providing a
<strong>bool</strong>() method.</p>
</blockquote>
<p>因此,如果搜索方法的结果直接反馈给<code>IF</code>,我们得到匹配的对象,<code>None</code>没有匹配的对象。因此,使用定义,对于<code>IF</code>,匹配将被评估为<code>True</code>,否则将被评估为<code>False</code>。因此,我们可以跳过那里的bool(),得到一个简化的版本,就像这样-</p>
<pre><code>[element for element in list1 if re.search(regexp, element)]
</code></pre>