如何在python case语句中运行代码块

发布于 2024-12-04 09:22:36 字数 387 浏览 1 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

谁把谁当真 2024-12-11 09:22:36

字典值必须是某种类型的对象。这意味着您本质上必须将要运行的代码封装在其他地方定义的函数中。您可以玩弄exec——例如,您可以创建一个字符串字典,然后exec来自该字典的字符串——但是我不会推荐它。

lambda 确实部分回答了您的问题,但 lambda 的适用性有限;除其他限制外,它只能创建单行函数。不过,对于非常简单的功能来说,它已经足够了。

>>> d = {
...      'a': lambda: 5 + 5,
...      'b': lambda: 10 + 10
...     }
>>> d['a']()
10

使用较长的代码块实现此目的的最佳方法就是定义一个函数或方法。

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 then exec a string from the dict, for example -- but I wouldn't recommend it.

lambda does partially answer your question, but lambda is limited in its applicability; it can only create one-line functions, among other limitations. Still, for very simple functions, it is adequate.

>>> d = {
...      'a': lambda: 5 + 5,
...      'b': lambda: 10 + 10
...     }
>>> d['a']()
10

The best way to do this with longer blocks of code is simply to define a function or method.

与君绝 2024-12-11 09:22:36

只需使用if...elif...else。没那么糟糕:

    if x == 'a':
        pass
    elif x == 'b':
        pass
    elif x == 'c':
        pass
    else:
        pass

Just use if...elif...else. It's not that bad:

    if x == 'a':
        pass
    elif x == 'b':
        pass
    elif x == 'c':
        pass
    else:
        pass
云淡风轻 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')

You need to put your code into functions. You could then create a dictionary of functions but there is already a concept to do that for you in Python: use a class.

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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文