擅长:python、mysql、java
<p>可以使用<a href="https://docs.python.org/3/library/functions.html#any" rel="noreferrer">^{<cd1>}</a>和<a href="https://docs.python.org/3/reference/expressions.html#grammar-token-generator_expression" rel="noreferrer">generator expression</a>:</p>
<pre><code>if not any(self.is_legal(x) for x in (l, u, r, d)):
</code></pre>
<p>或者,如果您喜欢<a href="https://docs.python.org/3/library/functions.html#all" rel="noreferrer">^{<cd2>}</a>而不是<code>any</code>:</p>
<pre><code>if all(not self.is_legal(x) for x in (l, u, r, d)):
</code></pre>
<p>不过,第一种解决方案似乎读起来更好一些。你知道吗</p>
<hr/>
<p>至于为什么您尝试的解决方案不起作用,Python中的<code>or</code>操作符的行为与您认为的不同。从<a href="https://docs.python.org/3/reference/expressions.html#grammar-token-or_test" rel="noreferrer">docs</a>:</p>
<blockquote>
<p>The expression <code>x or y</code> first evaluates <code>x</code>; if <code>x</code> is true, its value
is returned; otherwise, <code>y</code> is evaluated and the resulting value is
returned.</p>
</blockquote>
<p>因此,<code>self.is_legal(l or r or d or u)</code>只是将第一个truthy值传递给<code>self.is_legal</code>方法,而不是全部传递给它们。你知道吗</p>