细数10个隐藏在Python中的彩蛋

DeandreFrey 7年前
   <p><strong>1、使用re.DEBUG查看正则表达式的匹配过程</strong></p>    <p>正则表达式是Python的一大特色,但是调试起来会很痛苦,很容易得出一个bug。幸运的是,Python可以打印出正则表达式的解析树,通过re.debug来显示re.compile的完整过程。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/aeb54ae1c1e0ecee31a0d80050ad7d77.jpg"></p>    <p>一旦你理解了语法,你就可以发现你的错误。在这里我们可以看到[/font]忘了去除[]</p>    <p><strong>2、enumerate函数用于遍历列表中的元素以及它们的下标</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/fdfe3ce69b0fee3e52c3eae5c233fe23.jpg"></p>    <p><strong>3、对默认实参要多加小心</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/6028cc97e09923da9d9f5e523bdb24b4.jpg"></p>    <p>相反,你应该使用一个标记值表示“无定义”,来替换“[]”。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/092a421bc16df188a8f29aa3f1ed9414.jpg"></p>    <p><strong>4、对于C系的那些更喜欢括号而不是缩进的开发者,你只需使用以下一条命令:</strong></p>    <pre>  <code class="language-python">from __future__ import braces   </code></pre>    <p><strong>5、切片操作中的tricks</strong></p>    <pre>  <code class="language-python">a = [1,2,3,4,5] >>> a[::2] [1,3,5]   </code></pre>    <p>特殊的例子是x[::-1],它可以将列表反转</p>    <pre>  <code class="language-python">>>> a[::-1] [5,4,3,2,1]   </code></pre>    <p><strong>6、装饰器</strong></p>    <p>装饰器实现了在一个函数中调用其它函数或方法来增加功能性,从而修改参数或结果等,在函数定义前加上装饰器,只需一个“@”符号。</p>    <p>以下示例显示了一个print_args装饰器的用法:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/0a021a17f9fca46fedf7add86c2b6eb1.jpg"></p>    <p><strong>7、取参的trick</strong></p>    <p>你可以用*或者**来取出列表或字典作为函数参数</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/d032ab9337fc7080259f9f31325715a3.jpg"></p>    <p><strong>8、Exception else语句</strong></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/4bfc3f815e08f3aca8fc98c2f6b0ff66.jpg"></p>    <p>使用“else”比在“try”语句中添加多余的代码更好,因为它避免了意外获取不被try语句保护的异常…除了声明之外。</p>    <p><strong>9、嵌套列表推导式和生成器表达式</strong></p>    <pre>  <code class="language-python">[(i,j) for i in range(3) for j in range(i) ]    ((i,j) for i in range(4) for j in range(i) )   </code></pre>    <p>这些语句可以取代大量的嵌套循环代码块</p>    <p><strong>10、主要句式</strong></p>    <pre>  <code class="language-python">import this   </code></pre>    <p>下面让我们再诵读一遍Python之禅的要义(The Zen of Python, by Tim Peters):</p>    <pre>  <code class="language-python">Beautiful is better than ugly.    Explicit is better than implicit.    Simple is better than complex.    Complex is better than complicated.    Flat is better than nested.    Sparse is better than dense.   </code></pre>    <p> </p>    <p>来自:http://developer.51cto.com/art/201611/522095.htm</p>    <p> </p>