python - 从用户输入 python 中的二维坐标列表

标签 python input coordinates

用户需要输入一组坐标,例如 (0,0), (0,1), (1,1), (1,0)

我为此编写的代码如下所示:

def get_coords():
    #user_input = raw_input("Enter a list of points. For example (0,0) (0,1) (1,1) (1,0)\n")
    print "Enter a list of points. For example (0,0) (0,1) (1,1) (1,0)\n"
    uin = sys.stdin.readline().strip() 
    try:
    #coords = map(int, uin.split(' '))
    coords = [tuple(map(int, point.replace('(', '').replace(')', '').split(','))) for point in uin.split(' ')]
    return coords
    except ValueError:
    print "Please enter the coordinates in the format mentioned"
    exit()

我确定有更好、更优雅的方法来做到这一点?

最佳答案

',' 替换空格,然后应用 ast.literal_eval

>>> strs = '(0,0) (0,1) (1,1) (1,0)'
>>> from ast import literal_eval
>>> literal_eval(strs.replace(' ',','))
((0, 0), (0, 1), (1, 1), (1, 0))

使用正则表达式,这适用于任何数量的空格:

>>> import re
>>> strs = '(0, 0)  (0, 1) ( 1, 1)    ( 1,  0)'
>>> literal_eval(re.sub('(\))(\s+)(\()','\g<1>,\g<3>',strs))
((0, 0), (0, 1), (1, 1), (1, 0))

关于python - 从用户输入 python 中的二维坐标列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17050222/

相关文章:

python - Paramiko stdout.read给出 “AttributeError: '元组的对象没有属性 'read'”

python - 检查 python 中是否有任何属性的任何替代方法?

java - 如何在 Netbeans 中从 System.in (Java) 获取输入?

python - 当改变crs并用fig,ax绘图时,Geopandas绘图为空(没有fig,ax一切都很好)?

python opencv在使用第三方摄像头时无法显示视频

python - Pandas 数据框到 Excel 表

jquery - 使用 jQuery 设置复选框样式

events - Chrome 输入 [type=number] 和 onchange

javascript - Photoshop 脚本 : Coordinates of smart objects

javascript - 检查对象是否在 css border/css wrapper 内