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