擅长:python、mysql、java
<p>使用条件语句/三元运算符时,必须提供<code>else:</code>部分。尝试以下操作:</p>
<pre><code>return random.choice([i if len(i) == 9 else '' for i in words])
</code></pre>
<p>当然,您可能有机会<code>random.choice()</code>返回一个空字符串。如果希望列表理解仅返回<code>i</code><em>如果且仅当</em>长度为9,则可以将条件放在列表理解的末尾,而不是</em>需要<code>else:</code>:</p>
<pre><code>return random.choice([i for i in words if len(i) == 9])
</code></pre>