python 字典实现类似c的switch case】的更多相关文章

#python 字典实现类似c的switch def print_hi(): print('hi') def print_hello(): print('hello') def print_goodbye(): print('goodbye') choice = int(input('please input your choice:')) # 例子,不考虑输入错误的情况 # if ... elif 实现 if choice ==1: print_hi() elif choice ==2: pr…
python没有switch case 不过可以通过建立字典实现类似的功能 例子:根据输入的年月日,判断是该年中的第几天 y = int(input('请输入年:')) m = int(input('请输入月:'))d = int(input('请输入日:')) #建立月份对应天数增加的字典 实现了类似C语言中 switch...case的功能month_dict = {1:0, 2:31, 3:59, 4:90, 5:120, 6:151, 7:181, \ 8:212, 8:243, 10:…
if语句条件判断使用th:if,它会判断表达式是否成立,表达式的结果支持boolean.number.character.String及其他类型.满足下面情况,if语句成立:(1) 表达式的结果是数字且不是0(2) 表达式的结果是字符串且不是false.off.no.0(3) 表达式的结果是其他数据类型switch case语句(1) 类似Java的switch case语句:th:switch.th:case(2) 使用th:case="*"来表示默认值(3) 如果第一个th:cas…
Python不像C/C++,Java等有switch-case的语法.不过其这个功能,比如用Dictionary以及lambda匿名函数特性来替代实现. 字典+函数实现switch模式下的四则运算:(switch 下运算符只用判断一次,不同于 if .elsif 判断) 法1:-- 代码[root@bigdata01 ~]# cat t1.py #!/usr/bin/python#coding:utf-8 def add(x,y): return x+y def sub(x,y): return…
与我之前使用的所有语言都不同,Python没有switch/case语句.为了达到这种分支语句的效果,一般方法是使用字典映射: def numbers_to_strings(argument): switcher = { 0: "zero", 1: "one", 2: "two", } return switcher.get(argument, "nothing") 这段代码的作用相当于: function(argument)…
学习Python过程中,发现没有switch-case,过去写C习惯用Switch/Case语句,官方文档说通过if-elif实现.所以不妨自己来实现Switch/Case功能. 方法一 通过字典实现 def foo(var): return { 'a': 1, 'b': 2, 'c': 3, }.get(var,'error') #'error'为默认返回值,可自设置 方法二 通过匿名函数实现 def foo(var,x): return { 'a': lambda x: x+1, 'b':…
Why Doesn't Python Have Switch/Case? Tuesday, June 09, 2015 (permalink) Unlike every other programming language I've used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping: def numbers_to_stri…
不同于C语言和SHELL,python中没有switch case语句,关于为什么没有,官方的解释是这样的 使用Python模拟实现的方法: def switch_if(fun, x, y):    if fun == 'add':        return x + y    elif fun == 'sub':        return x - y    elif fun == 'mul':        return x * y    elif fun == 'div':       …
python的字典有些类似js对象 dict1 = {} dict1['one']= '1-one' dict1[2] = '2-tow' tinydict = {'name':'tome','code':1,2:200,2.2:2.222} #像JavaScript中的对象 print(dict1, tinydict) print(tinydict[2],tinydict[2.2]) # 可以使用整数.浮点数作为key print(tinydict.keys()) print(tinydict…
字典dict是Python中使用频率非常高的数据结构,关于它的使用,也有许多的小技巧,掌握这些小技巧会让你高效地的使用dict,也会让你的代码更简洁. 1.默认值 假设name_for_userid存放的是name和id的映射关系: name_for_userid = { 1: '张三', 2: '李四', 3: '王五', } 获取name_for_userid中的某一个id的name,最简单的方式: name_for_userid[1] '张三' 这种方式虽然简单,但有一个不便之处就是,如果…