【问题标题】:Connecting string and number commands in a list在列表中连接字符串和数字命令
【发布时间】:2021-11-25 09:02:30
【问题描述】:

我正在尝试添加移动命令以及必须移动到列表中的数量。我无法弄清楚如何获得所需的输出。以下是我的代码

import re

history_list = []

gameOn = True

while gameOn:
    user_command = input("Please enter a direction and amount to move: ")
    history_list += re.sub("[^\w]", " ",  user_command).split()
    if user_command.lower() == "off":
        break

print(history_list)

所以我有 2 个基本的移动命令,即“前进”和“后退”,它们还需要一个我想要向前或向后移动的数字,然后是一个向左或向右转的“左”和“右”命令。 假设我输入“forward 20”然后“right”然后“back 15” 我得到的是

['forward','20,'right','back','15']

但我想要的是

['forward 20','right','back 15']

【问题讨论】:

  • 你为什么用split()
  • 将user_command拆分成一个列表
  • 如果用户一个一个输入命令,你能不能像这样添加它们:history_list.append("forward 20")history_list.append("right")等?也许您需要添加一个单独的函数来验证或格式化用户输入的内容,但您现在拥有的拆分似乎没有必要。

标签: python python-3.x list


【解决方案1】:

感觉就像您正在使用带有正则表达式和拆分的复杂构造,因为您认为需要将其附加到列表中。不是,你可以这样改写:

history_list = []

gameOn = True

while gameOn:
    user_command = input("Please enter a direction and amount to move: ")
    history_list.append(user_command)
    if user_command.lower() == "off":
        break
    
print(history_list)

但是,由于您从用户那里获取输入,您需要对输入进行一些验证,其中正则表达式和 split 可能有用,但是一旦您验证了该输入,您就可以重新添加初始输入如图所示。

【讨论】:

    猜你喜欢
    • 2018-05-15
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 2018-08-30
    相关资源
    最近更新 更多