Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有类似于“a”的东西吗;无效lambda“;用Python?_Python_Python 2.7_Dictionary_Lambda_Void - Fatal编程技术网

有类似于“a”的东西吗;无效lambda“;用Python?

有类似于“a”的东西吗;无效lambda“;用Python?,python,python-2.7,dictionary,lambda,void,Python,Python 2.7,Dictionary,Lambda,Void,也就是说,lambda不接受任何输入,也不返回任何内容 我在考虑用Python模拟switch语句的巧妙方法。以下是我尝试过的(没有用): lambda函数的内容必须是单个表达式;不允许有任何声明。此外,是Python 2.x中的一条语句。这意味着您不能在lambda中使用它 如果您想使用Python 3.x,您可以从以下位置导入它: 现在,print可以在lambdas内部使用,因为它是一个函数: statement = { "Bob": lambda: print("Looking

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

我在考虑用Python模拟switch语句的巧妙方法。以下是我尝试过的(没有用):


lambda函数的内容必须是单个表达式;不允许有任何声明。此外,是Python 2.x中的一条语句。这意味着您不能在lambda中使用它

如果您想使用Python 3.x,您可以从以下位置导入它:

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

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]

对于更复杂的
开关
类应用程序,
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,像函数一样,返回一些东西;默认值为
None
。只需忽略返回值。您的问题是试图使用只能使用表达式的语句。感谢您的澄清,但您可能需要在其中添加逗号
print {
    "Bob": "Looking good, Bob!",
    "Jane": "Greetings, Jane!",
    "Derek": "How goes it, Derek?"
}[person]
statement = {
    "Bob": "Looking good, Bob!",
    "Jane": "Greetings, Jane!",
    "Derek": "How goes it, Derek?"
}[person]
print statement
class Greeter(object):
    ... 
    def _greet_Bob(self): ...
    def _greet_Jane(self): ...
    def _greet_Derek(self): ...

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