Python中有没有类似于“voidlambda”的东西?

2024-05-20 12:11:40 发布

您现在位置:Python中文网/ 问答频道 /正文

也就是说,lambda不接受输入也不返回任何内容。在

我在想一些聪明的方法来模仿Python中的switch语句。以下是我所尝试的(徒劳):

statement = {
    "Bob": lambda: print "Looking good, Bob!",
    "Jane": lambda: print "Greetings, Jane!",
    "Derek": lambda: print "How goes it, Derek?"
}[person]()

Tags: 方法lambda内容derek语句howstatementbob
2条回答

对于这个用例,您最好执行以下操作:

print {
    "Bob": "Looking good, Bob!",
    "Jane": "Greetings, Jane!",
    "Derek": "How goes it, Derek?"
}[person]

或者

^{pr2}$

当然,对于更复杂的switch类应用程序,dict可以保存函数引用。在

我还喜欢将函数名写成字符串:

class Greeter(object):
    ... 
    def _greet_Bob(self): ...
    def _greet_Jane(self): ...
    def _greet_Derek(self): ...

    def greet(self,person):
        getattr( self, "_greet_"+person )()  

lambda函数的内容必须是单个表达式;不允许使用语句。而且,^{}是Python2.x中的一个语句,这意味着您不能在lambda中使用它。在

如果要使用python3.x^{} function,可以从^{}导入它,如下所示:

# Add this line to the top of your script file
from __future__ import print_function

现在,print可以在lambdas中使用,因为它是一个函数:

^{pr2}$

相关问题 更多 >