Heim >Backend-Entwicklung >Python-Tutorial >python 有哪些优雅的代码实现 ?
python 有哪些优雅的代码实现 ?以前在一篇博客中学习过。记得这是有一个统一的名称的。不过忘了
举个常用的例子 [i for i in list if not…… ]。
这种代码写的很爽,但感觉自己掌握的不全。所以特来问一下
<code class="language-python"><span class="k">def</span> <span class="nf">add</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
<span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span>
</code>
1. map、reduce、filter三兄弟和lambda匿名函数,拯救缓慢的for循环(然而其实也并没有特别快),伪装函数式语言(然而实际上还是OO),并且[哔]<code class="language-python3"><span class="k">def</span> <span class="nf">f</span><span class="p">(</span><span class="n">n</span><span class="p">):</span>
<span class="k">if</span> <span class="n">n</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
<span class="k">return</span> <span class="mi">1</span>
<span class="k">return</span> <span class="n">n</span> <span class="o">*</span> <span class="n">f</span><span class="p">(</span><span class="n">n</span> <span class="o">-</span> <span class="mi">1</span><span class="p">)</span>
</code>
<code class="language-python3"><span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span>
</code>
读读 Python documentation 里的 The Python Language Reference 你就明白了,这都是很一般的写法。