【发布时间】: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