【问题标题】:Use input as parameters for a function called by a dictionary将输入用作字典调用的函数的参数
【发布时间】:2012-09-26 07:54:11
【问题描述】:

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

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 个不同的函数来进行移动,然后 ' south' 作为该函数中方向的参数。

【问题讨论】:

  • 那你为什么要定义moveWest等呢?

标签: python dictionary


【解决方案1】:

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]()

【讨论】:

  • @PierreGM 正是我今天早上的感受。添加了支票。
  • 太棒了,非常感谢,设法也能够使用 function_dict[command](),赞 :)
【解决方案2】:

这个怎么样:

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])

基本上我只是尝试用空格分割输入并通过第一部分决定命令的类型(movewaitlook em> ...)。第二部分用作参数。

【讨论】:

    【解决方案3】:

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

    如果您无法使用cmd 模块,您将不得不自己解析命令行。您可以使用command.split() 执行此操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 2017-11-02
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多