这篇文章主要介绍了 Python 中实现 switch 功能实例解析,具有一定借鉴价值, 需要的朋友可以参考下
前言
今天在学习 python 的过程中,发现 python 没有 switch 这个语法.于是就想在 python 中如何才能实现这个功能呢?
正文
本文中我们对 switch 的使用模拟为正常的数据库的增删改查操作的对应,如'select
对应'select action'等.
1. 简单的 if-else
正如我们所知,python 中有 if 语句,而且当时学习 C 的时候,学到 if-else 时引出的的替代品就是 switch,两者可以完美的互相替代, 需要注意的是在 python 中 else if 简化成了 elif.如下所示:
2. 使用字典
#!/usr/bin/env python
user_cmd = raw_input("please input your choice:\n")
if usercmd == "select"
ops = "select action"
elif usercmd == "update"
ops = "update action"
elif usercmd == "delete"
ops = "delete action"
elif usercmd == "insert"
ops = "insert action"
else
ops = "invalid choice!"
print ops
`</pre>
这里我们使用到了字典的函数:dict.get(key, default=None).key-- 字典中要查找的值,default-- 如果指定键的值不存在时,返回该默认值.如下所示:
3. 使用 lambda 函数结合字典
#!/usr/bin/env python
usercmd = raw_input("please input your choice:\n")
dic = {'select':'select action','update':'update action','delete':'delete action','insert':'insert action'}
defaultitem = 'invalid choice!'
ops = dic.get(usercmd,defaultitem)
print ops
lambda 的一般形式是关键字 lambda 后面跟一个或多个参数,紧跟一个冒号,以后是一个表达式.lambda 是一个表达式而不是一个语句.它能够出现在 Python 语法不允许 def 出现的地方,这里就不再多加描述.如下所示:
总结
#!/usr/bin/env python
usrcmd = raw_input("please input your choice:\n")
dic = {'select': lambda : "select action",
'update': lambda : "update action",
'delete': lambda : "delete action",
'insert': lambda : "insert action"}
print cho[usr_cmd]()
以上就是本文关于 Python 中实现 switch 功能实例解析的全部内容,希望对大家有所帮助.感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出.感谢朋友们对本站的支持!
来源: http://www.phperz.com/article/18/0128/362737.html