如何在python case语句中运行代码块
我是 python 新手,我真的很喜欢使用字典而不是 switch/case 语句的概念,但有一个问题我无法弄清楚
假设我们有一个“pythonic case”语句
{
'a': somemethod,
'b': othermethod
}['a']()
这工作正常,但我可以'不知道如何像其他语言(如 java)一样运行某些代码块,看起来像这样
{
'a': { some commands here }
'b': { other commands here that are executed }
}['a']
也许 lambda 可以提供帮助?
太感谢了
I'm new to python and I really like concept of using dictionaries instead of switch/case statements, but there is one problem I can't figure out
Let's say we have a 'pythonic case' statement
{
'a': somemethod,
'b': othermethod
}['a']()
This works fine, but I can't figure out how to run some block of code like in other languages like java, something which would look like this
{
'a': { some commands here }
'b': { other commands here that are executed }
}['a']
Maybe lambda could help?
Thank you so much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
云淡风轻2024-12-11 09:22:36
您需要将代码放入函数中。然后,您可以创建一个函数字典,但 Python 中已经有一个概念可以为您做到这一点:使用类。
class Foo:
def cmd_a(self): ...
def cmd_b(self): ...
def cmd_c(self): ...
def default_action(self): ...
def execute(self, cmd):
action = getattr(self, 'cmd_'+cmd, self.default_action)
return action()
foo = Foo()
foo.execute('a')
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
字典值必须是某种类型的对象。这意味着您本质上必须将要运行的代码封装在其他地方定义的函数中。您可以玩弄
exec
——例如,您可以创建一个字符串字典,然后exec
来自该字典的字符串——但是我不会推荐它。lambda 确实部分回答了您的问题,但 lambda 的适用性有限;除其他限制外,它只能创建单行函数。不过,对于非常简单的功能来说,它已经足够了。
使用较长的代码块实现此目的的最佳方法就是定义一个函数或方法。
Dictionary values have to be objects of some kind. This means that you essentially must encapsulate the code you want to run within a function defined elsewhere. You could toy with
exec
-- you could create a dict of strings, and thenexec
a string from the dict, for example -- but I wouldn't recommend it.lambda
does partially answer your question, butlambda
is limited in its applicability; it can only create one-line functions, among other limitations. Still, for very simple functions, it is adequate.The best way to do this with longer blocks of code is simply to define a function or method.