从用户输入python中的2D坐标列表

时间:2013-06-11 17:30:30

标签: 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()

我确信有更好,更优雅的方式来做到这一点?

3 个答案:

答案 0 :(得分:2)

','替换空格,然后应用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))

答案 1 :(得分:2)

>>> from ast import literal_eval
>>> uin = raw_input("coords: ").split()
coords: (0,0) (0,1) (1,1) (1,0)
>>> uin
['(0,0)', '(0,1)', '(1,1)', '(1,0)']
>>> coords = [literal_eval(coord) for coord in uin]
>>> coords
[(0, 0), (0, 1), (1, 1), (1, 0)]

在你的文件中,你可以写这个。用你喜欢的任何东西替换提示。

from ast import literal_eval
try:
    coords = [literal_eval(coord) for coord in raw_input("coords: ").split()]
except ValueError:
    print "Please enter the coordinates in the format mentioned"
    exit()
如果代码不安全,请

literal_eval() raises an exceptionSee the docs.

常规eval()很糟糕,因为它可以执行用户输入的任意代码!

答案 2 :(得分:1)

只需在元组之间添加逗号即可,您可以安全地将字符串评估为元组元组:

import ast

def get_coords():
    print "Enter a list of points. For example (0,0), (0,1), (1,1), (1,0)"
    points = raw_input()

    while True:
        try:
            return ast.literal_eval(points)
        except SyntaxError:
            print "Please enter the coordinates in the format mentioned"

你会得到类似于的结果:

((0, 0), (0, 1), (1, 1), (1, 0))

如果您绝对需要列表,请将其传递给list()

            return list(ast.literal_eval(points))