[英]How may i use switch statement in python (for multiple case same value)[python]
我想在 python 中使用一个开关,我该如何使用它。 假设如果我想为 90 分以上的学生分配一个评分系统将获得低于 A 的成绩,使用 switch 将获得 B
请帮忙!!!
Python 没有 switch 语句。 要在 Python 中实现类似的功能,您可以使用if
/ elif
/ else
(这对您的示例非常有用)或使用字典的查找表。
您可以使用以下函数定义模拟 switch 语句:
def switch(v): yield lambda *c: v in c
您可以在 C 风格中使用它:
x = 3
for case in switch(x):
if case(1):
# do something
break
if case(2,4):
# do some other thing
break
if case(3):
# do something else
break
else:
# deal with other values of x
或者您可以使用 if/elif/else 模式而没有中断:
x = 3
for case in switch(x):
if case(1):
# do something
elif case(2,4):
# do some other thing
elif case(3):
# do something else
else:
# deal with other values of x
它对于函数调度可以特别有表现力
functionKey = 'f2'
for case in switch(functionKey):
if case('f1'): return findPerson()
if case('f2'): return editAccount()
if case('f3'): return saveChanges()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.