Python 将输入用作字典调用的函数的参数

Python 将输入用作字典调用的函数的参数,python,dictionary,Python,Dictionary,我使用字典允许用户输入一些东西,但下一个问题是使用第二个单词作为被调用函数的参数。目前,我有: def moveSouth(): Player.makeMove("south") def moveNorth(): Player.makeMove("north") def moveEast(): Player.makeMove("east") def moveWest(): Player.makeMove("west") function_dict = {'mov

我使用字典允许用户输入一些东西,但下一个问题是使用第二个单词作为被调用函数的参数。目前,我有:

def moveSouth():
    Player.makeMove("south")
def moveNorth():
    Player.makeMove("north")
def moveEast():
    Player.makeMove("east")
def moveWest():
    Player.makeMove("west")

function_dict = {'move south':moveSouth, 'wait':wait, 'sleep':sleep,
                 'move north':moveNorth, 'move':move, 'look':look,
                 'move east':moveEast,
                 'move west':moveWest}
要获取输入,请执行以下操作:

command = input("> ")
command = command.lower()
try:
   function_dict[command]()
except KeyError:
   i = random.randint(0,3)
   print(responses[i])
然而,我希望有一种方法,当用户输入“向南移动”时,它使用第一个单词调用函数,然后使用“向南”作为该函数方向的参数,而不是必须有4个不同的函数来进行移动。

command = input("> ")
command_parts = command.lower().split(" ")
try:
   if len(command_parts) == 2 and command_parts[0] == "move":
       Player.makeMove(command_parts[1])
   else:
       function_dict[command_parts[0]]()
except KeyError:
   i = random.randint(0,3)
   print(responses[i])

本质上,我只是尝试将输入分割成一个空格,并通过第一部分(move、wait、look…)决定命令的类型。第二部分用作参数。

对于这种类型的命令行处理,您可以轻松使用
cmd
模块。它允许您通过创建类似于
do
的方法来创建命令,并将行的其余部分作为参数

如果不能使用
cmd
模块,则必须自己解析命令行。您可以使用
command.split()

split()
输入,然后分别传递每个部分

command = input("> ")
user_input = command.lower().split()
command = user_input[0]
if len(user_input) > 1:
    parameter = user_input[1]
    function_dict[command](parameter)
else:
    function_dict[command]()

那么,你为什么要定义
moveWest
和其他人呢?@PierreGM这正是我今天早上的感受。添加了一个检查。太棒了,非常感谢您的帮助,成功地使用了函数_dict[command](),很荣幸:)