python为什么不需要三目运算符和switch
下面小编就为大家带来一篇浅谈python为什么不需要三目运算符和switch。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
对于三目运算符(ternary operator),python可以用conditional expressions来替代
如对于x
1if x<p></p><p>注: conditional expressions是在python 2.5之前引入的,所以以上代码仅适用于2.5以及之后的版本</p><p><span>立即学习</span>“<a href="https://pan.quark.cn/s/00968c3c2c15" style="text-decoration: underline !important; color: blue; font-weight: bolder;" rel="nofollow" target="_blank">Python免费学习笔记(深入)</a>”;</p><p>对于2.5之前的版本,可以用下面这种形式</p><p class="jb51code"></p><pre class="brush:py;">X<p></p><p>对于switch,我们完全可以用dictionary来实现,看下面的例子</p><p class="jb51code"></p><pre class="brush:py;">>>>def switch(choice):return dict(enumerate(range(4)))[choice]>>> switch(1)>>> switch(0)values = { value1: do_something1, value2: do_something2, ... valueN: do_somethingN, }values.get(var, do_default_something)()