• 当前标签:switch

程序开发 Python的switch替换方案、列表推导式、字典推导式

switch替换方案 day = 8 def get_sunday(): return 'Sunday' def get_monday(): return 'Monday' def get_tuesday(): return 'Tuesday' def get_default(): return 'Unkown' switcher = { 0: get_sunday, 1: get_monday, 2: get_tuesday } day_name = switcher.get(day, get_default)() print(day_name) 列表推导式 # 列表推导式 # 集合推导式 # set 也可以被推导 # dict a = [1,2,3,4,5,6,7,8] aa = {1,2,3,4,5,6,7,8} aaa = (1,2,3,4,5,6,7,8) b = [i**2 for i in a] c = [i**2 for i in a if i >= 5] print(b) print(c) bb = {i**2 for i in aa} bbb = [i**2 for i in aaa] print(bb) print(bbb) 字典推导式 students = { '张三': 18, '李四': 22, '王五': 16 } b = [key for key,value in students.items()] bb = {value:key for key,value in students.items()} print(b) # ['张三', '李四', '王五'] print(bb) # {18: '张三', 22: '李四', 16: '王五'} # 不推荐元组 c = (key for key,value in students.items()) for x in c: print(x)

2020-02-19 23:37:28 139 0 1
阅读详情
  • 1
前往