擅长:python、mysql、java
<p>下面是我最喜欢的几个例子,其中赋值表达式可以使代码更简洁、更易于阅读:</p>
<h3><code>if</code>语句</h3>
<p>之前:</p>
<pre class="lang-py prettyprint-override"><code>match = pattern.match(line)
if match:
return match.group(1)
</code></pre>
<p>之后:</p>
<pre class="lang-py prettyprint-override"><code>if match := pattern.match(line):
return match.group(1)
</code></pre>
<h3>无限<code>while</code>语句</h3>
<p>之前:</p>
<pre class="lang-py prettyprint-override"><code>while True:
data = f.read(1024)
if not data:
break
use(data)
</code></pre>
<p>之后:</p>
<pre class="lang-py prettyprint-override"><code>while data := f.read(1024):
use(data)
</code></pre>
<p>有<a href="https://www.python.org/dev/peps/pep-0572/#examples" rel="noreferrer">other good examples in the PEP</a>。</p>