[英]How do you include a command in a python dictionary
I'm creating a smart Chatbot. 我正在创建一个智能的聊天机器人。 That part of information is irrelevant, however. 但是,那部分信息无关紧要。 What I'm trying to do is call on an instruction from within a dictionary - I'll show you: 我想做的是从字典中调用指令-我将向您展示:
dictionary = ["command1": "print("I just called command1!")]
dictionary["command1"]
Sort of like that. 有点像。 Obviously you cannot do that. 显然,您无法做到这一点。 I want to be able to have a dictionary of different commands which will run when you use dictionary[whatever_command you want_in_here] 我希望能够拥有一个包含不同命令的字典,当您使用字典时,这些命令将运行[无论您要在此处使用什么命令]
Do you see what I mean? 你明白我的意思吗?
I could use functions, but clearly that would take up a whole lot of space and lots of code which I cannot afford when there are so many responses in my Chatbot. 我可以使用函数,但是很显然,这会占用大量空间和大量代码,而当我的Chatbot中有如此多的响应时,我将负担不起。
I really need to know how to do this in a simple way. 我真的需要知道如何以一种简单的方式做到这一点。
Pls. 请 :) :)
Store instructions as anonymous functions: 将指令存储为匿名函数:
dictionary = {
"command1": lambda: print("I just called command1!"),
"command2": lambda: print("I just called command2!")
}
command = input('Enter command: ')
dictionary[command]()
If you're just looking to print strings, you're much better off doing something like: 如果您只是想打印字符串,那么最好做以下事情:
dictionary = {"command1": "I just called command1!"}
print(dictionary["command1"])
but if you need to parse actual functions, you can, as @Uriel Eli said in the other answer, using a lambda. 但是,如果您需要解析实际函数,则可以如@Uriel Eli在另一个答案中所说的那样使用lambda。
mylist = []
dictionary = {"command1": lambda: print("I just called command1"), "command2": lambda: mylist.append("Here's an appended string!")}
dictionary["command1"]()
dictionary["command2"]()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.