浅谈python为什么不需要三目运算符和switch
作者:jingxian 时间:2022-04-02 16:22:39
对于三目运算符(ternary operator),python可以用conditional expressions来替代
如对于x<5?1:0可以用下面的方式来实现
1if x<5else 0
注: conditional expressions是在python 2.5之前引入的,所以以上代码仅适用于2.5以及之后的版本
对于2.5之前的版本,可以用下面这种形式
X<5and1or 0
对于switch,我们完全可以用dictionary来实现,看下面的例子
>>>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)()
标签:python,三目运算符,switch
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python 共享变量加锁、释放详解
2022-08-25 09:19:26
![](https://img.aspxhome.com/file/2023/2/103622_0s.png)
Python接口自动化之浅析requests模块post请求
2022-12-10 21:10:05
![](https://img.aspxhome.com/file/2023/0/87740_0s.png)
python3中str(字符串)的使用教程
2021-07-19 00:28:47
老生常谈Python进阶之装饰器
2022-05-20 10:51:23
关于JS中的事件--Event对象
2008-03-16 14:22:00
PHP 危险函数全解析
2023-11-20 15:36:12
浅谈Keras中fit()和fit_generator()的区别及其参数的坑
2022-04-18 07:22:26
![](https://img.aspxhome.com/file/2023/3/88903_0s.jpg)
python编程进阶之类和对象用法实例分析
2022-04-01 23:59:03
如何才能有效对抗MySQL数据库的解密高手
2009-05-22 18:21:00
Go 代码生成工具详解
2023-06-18 21:11:48
![](https://img.aspxhome.com/file/2023/8/89028_0s.png)
python使用plot绘制未来15天气温折线图
2022-11-06 02:09:41
![](https://img.aspxhome.com/file/2023/0/93620_0s.png)
python实现图片横向和纵向拼接
2021-12-20 20:53:30
![](https://img.aspxhome.com/file/2023/3/112993_0s.jpg)
haskell实现多线程服务器实例代码
2021-08-06 00:08:22
python3中超级好用的日志模块-loguru模块使用详解
2022-03-08 19:08:54
![](https://img.aspxhome.com/file/2023/1/115471_0s.jpg)
Python‘==‘ 及 ‘is‘相关原理解析
2021-10-11 15:16:59
php使用递归与迭代实现快速排序示例
2023-11-14 09:46:31
Python如何设置指定窗口为前台活动窗口
2022-01-22 02:20:02
Python手机号码归属地查询代码
2021-05-02 05:00:30
![](https://img.aspxhome.com/file/2023/6/67786_0s.png)
python实现定时发送qq消息
2021-08-17 00:10:34
![](https://img.aspxhome.com/file/2023/1/109501_0s.jpg)
python图形用户界面tkinter之按钮Button的使用说明
2022-09-14 06:48:28
![](https://img.aspxhome.com/file/2023/4/106974_0s.png)