3

用户需要输入一组坐标,例如 (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()

我敢肯定有更好,更优雅的方式来做到这一点?

4

3 回答 3

2

Replace the spaces with ',' and then apply 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))

Using regex, this would work on any amount of spaces:

>>> 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))
于 2013-06-11T17:37:59.077 回答
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() 如果代码不安全,则引发异常。请参阅文档。

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

于 2013-06-11T17:44:34.400 回答
1

Just add in commas between the tuples and you can safely evaluate the string into a tuple of tuples:

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"

You'll get a result similar to:

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

And if you absolutely need a list, just pass it through list():

            return list(ast.literal_eval(points))
于 2013-06-11T17:37:15.217 回答