python - 如何读取包含括号中坐标的用户输入
问题描述
我正在制作一个非常简单的游戏,您可以在其中制作一个数字表并隐藏用户需要找到的炸弹。
这是代码:
import random
def game(rows, colums):
table = (rows * colums - 1) * [' '] + ['bomb']
random.shuffle(table)
while True:
position = input('Enter next position (x, y):')
bombposition = position.split()
if table[int(bombposition[0])*colums + int(bombposition[1])] == 'bomb':
print('you found the bomb!')
break
else:
print('no bomb at', position)
错误:
game(1,0)
Enter next position (x, y):>?
(1,0)
Traceback (most recent call last):
File "input", line 1, in <module>
File "input", line 8, in game
ValueError: invalid literal for int() with base 10: '(1,0)'
解决方案
首先split
默认使用空格,所以用逗号分隔你需要position.split(',')
. 尽管即使那样,如果您在 上拆分,您split
仍然会将(
and)
附加到您的字符串上,例如在您的情况下'(1'
and '0)'
。我建议也许使用正则表达式从您的输入中提取数字
import re
position = input('Enter next position (x, y):')
match = re.match(r'\((\d+)\, *(\d+)\)', position)
if match:
x = int(match.group(1))
y = int(match.group(2))
else:
# input didn't match desired format of (x, y)
推荐阅读
- xcode - iOS:如何快速获取 cocoapods 的更新版本
- javascript - 算法 - 搜索和替换字符串
- javascript - 材质 UI 选项卡不适用于滚动到
- python - Flask SQLAlchemy 不会创建记录(DateTimeField)
- php - 如何在 php 中从 json {"x":"y"} 到 {x:y} 中删除双引号
- css - 基于数组中的键值对有条件地应用css类,VueJS
- mysql - 从部署在 Kubernetes 上的应用程序访问外部 MySQL 实例
- c# - 悬停在listview wpf中时如何删除颜色边框和背景
- git - 删除提交和文件以减少 repo 大小
- python - 为多个任务运行 ML 模型的有效方法