2024-05-20 12:11:40 发布
网友
也就是说,lambda不接受输入也不返回任何内容。在
我在想一些聪明的方法来模仿Python中的switch语句。以下是我所尝试的(徒劳):
statement = { "Bob": lambda: print "Looking good, Bob!", "Jane": lambda: print "Greetings, Jane!", "Derek": lambda: print "How goes it, Derek?" }[person]()
对于这个用例,您最好执行以下操作:
print { "Bob": "Looking good, Bob!", "Jane": "Greetings, Jane!", "Derek": "How goes it, Derek?" }[person]
或者
当然,对于更复杂的switch类应用程序,dict可以保存函数引用。在
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中使用,因为它是一个函数:
print
对于这个用例,您最好执行以下操作:
或者
^{pr2}$当然,对于更复杂的
switch
类应用程序,dict
可以保存函数引用。在我还喜欢将函数名写成字符串:
lambda函数的内容必须是单个表达式;不允许使用语句。而且,^{} 是Python2.x中的一个语句,这意味着您不能在lambda中使用它。在
如果要使用python3.x^{} function ,可以从^{} 导入它,如下所示:
现在,
^{pr2}$print
可以在lambdas中使用,因为它是一个函数:相关问题 更多 >
编程相关推荐