简体   繁体   English

如何在 dict/set/list 中实现 lambda function

[英]How do I implement a lambda function inside a dict/set/list

So I am coding a user-input system that can accept commands.所以我正在编写一个可以接受命令的用户输入系统。 Further detail on it won't be revealed.关于它的更多细节不会被透露。

One of the things I want to do is implement a lambda function inside a dictionary.我想做的一件事是在字典中实现 lambda function 。

Here's an example of what I want to do:这是我想做的一个例子:

dictionary = {

   "command_a": lambda:

               stuff_to_do = ""
               # do stuff 
               return stuff_to_do
   
}

And when the user enters `command_a', it'd call the function, as follows:当用户输入 `command_a' 时,它会调用 function,如下:

command = input("Command")
if command in dictionary.keys():
  dictionary[command]()

But I get:但我得到:

  File "<stdin>", line 5
    stuff_to_do = ""
                ^
SyntaxError: invalid syntax

The code seems logical.代码似乎合乎逻辑。 The dictionary stores a function under the "command_a" key, but it doesn't work.字典在“command_a”键下存储了一个 function,但它不起作用。 Is it permissible to do so in python?在 python 中是否允许这样做? If yes, then how to?如果是,那怎么办?

A lambda can only define a function in the form of a single expression, eg:一个lambda只能以单个表达式的形式定义一个 function,例如:

dictionary = {
   "command_a": (lambda: "stuff to do")
}

If you want to define a function that consists of multiple statements, you need to use a def statement:如果要定义一个包含多个语句的 function ,则需要使用def语句:

def command_a():
    stuff_to_do = ""
    # do stuff 
    return stuff_to_do
   
dictionary = {
   "command_a": command_a
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM