Python如何将输入的移动命令与对应数值按组合并存入列表
代码调整方案
问题原因
你原有代码的问题在于:用split()将每次输入的字符串拆分为了单个单词的列表,再通过+=操作把拆分后的元素逐个追加到history_list中,因此会把forward和20这类指令与数值拆分为两个独立的列表元素。
调整思路
不需要拆分每次输入的指令,将经过格式清理的整行有效指令作为单个元素存入列表即可,同时提前判断退出指令off,避免将退出指令也存入列表。
修改后代码
import re history_list = [] gameOn = True while gameOn: user_command = input("Please enter a direction and amount to move: ") # 匹配到退出指令直接终止循环,不存入列表 if user_command.lower() == "off": break # 清理输入格式:移除特殊字符、合并连续空格、去除首尾多余空格 cleaned_command = re.sub(r'\s+', ' ', re.sub(r'[^\w\s]', '', user_command)).strip() # 整条指令作为单个元素加入列表 history_list.append(cleaned_command) print(history_list)
效果验证
依次输入forward 20、right、back 15、off,输出结果为:['forward 20', 'right', 'back 15'],完全符合预期。
内容的提问来源于stack exchange,提问作者Cecil Shepherd
相关产品推荐
相关产品推荐

