Mar*_*n08 5 python switch-statement
我想通过将其与正则表达式序列进行匹配来处理字符串.因为我试图避免嵌套if-then,我正在考虑切换案例.如何在Python中编写以下结构?谢谢
switch str:
case match(regex1):
# do something
case match(regex2):
# do sth else
Run Code Online (Sandbox Code Playgroud)
我知道Perl允许一个人这样做.是Python吗?
首先考虑为什么Python中没有case语句.所以重置大脑并忘记它们.
您可以使用对象类,函数装饰器或使用函数字典来实现相同或更好的结果.
这是一个简单的例子:
#!/usr/bin/env python
import re
def hat(found):
if found: print "found a hat"
else: print "no hat"
def cat(found):
if found: print "found a cat"
else: print "no cat"
def dog(found):
if found: print "found a dog"
else: print "no dog"
st="""
Here is the target string
with a hat and a cat
no d o g
end
"""
patterns=['hat', 'cat', 'dog']
functions=[hat,cat,dog]
for pattern,case in zip(patterns,functions):
print "pattern=",pattern
case(re.search(pattern,st))
Run Code Online (Sandbox Code Playgroud)
C风格案例/开关语句也"落空",例如:
switch(c) {
case 'a':
case 'b':
case 'c': do_abc();
break;
... other cases...
}
Run Code Online (Sandbox Code Playgroud)
使用元组和可调用的列表,您可以获得类似的行为:
st="rat kitten snake puppy bug child"
def proc1(st): print "cuddle the %s" % st
def proc2(st): print "kill the %s" % st
def proc3(st): print "pick-up the %s" % st
def proc4(st): print "wear the %s" % st
def proc5(st): print "dispose of the %s" %st
def default(st): print "%s not found" % st
dproc={ ('puppy','kitten','child'):
[proc3, proc1],
('hat','gloves'):
[proc3, proc4],
('rat','snake','bug'):
[proc2, proc3, proc5]}
for patterns,cases in dproc.iteritems():
for pattern in patterns:
if re.search(pattern,st):
for case in cases: case(pattern)
else: default(pattern)
print
Run Code Online (Sandbox Code Playgroud)
这使得找到的项目的顺序正确:1)捡起孩子,抱抱孩子; 2)杀死老鼠,拿起老鼠......用可理解的语法用C switch语句做同样的事情是很困难的.
还有许多其他方法可以模仿C switch语句.这是一个(对于整数)使用函数装饰器:
case = {}
def switch_on(*values):
def case_func(f):
case.update((v, f) for v in values)
return f
return case_func
@switch_on(0, 3, 5)
def case_a(): print "case A"
@switch_on(1,2,4)
def case_b(): print "case B"
def default(): print "default"
for i in (0,2,3,5,22):
print "Case: %i" % i
try:
case[i]()
except KeyError:
default()
Run Code Online (Sandbox Code Playgroud)
用Perl 编写Perl中的 Larry Wall,Tom Christiansen,Jon Orwant来理解Perl中的上下文:
在你使用语言原生的习语之前,你将是悲惨的编程Python ...
您正在寻找pyswitch(免责声明:我是作者)。有了它,您可以执行以下操作,这与您在问题中给出的示例非常接近:
from pyswitch import Switch
mySwitch = Switch()
@myswitch.caseRegEx(regex1)
def doSomething(matchObj, *args, **kwargs):
# Do Something
return 1
@myswitch.caseRegEx(regex2)
def doSomethingElse(matchObj, *args, **kwargs):
# Do Something Else
return 2
rval = myswitch(stringYouWantToSwitchOn)
Run Code Online (Sandbox Code Playgroud)
我链接的 URL 上给出了一个更全面的示例。pyswitch 不仅限于切换正则表达式。在内部,pyswitch 使用类似于其他人上面给出的示例的调度系统。我只是厌倦了每次需要那种调度系统时都必须一遍又一遍地重写相同的代码框架,所以我编写了 pyswitch。
| 归档时间: |
|
| 查看次数: |
6414 次 |
| 最近记录: |