2013-03-22 27 views
1

我有以下形式的字符串:从字符串创建的元组(X,Y)的列表

POLYGON((159.5 534.5,157.5 535.5,157.5 554.5,155.5 557.5,...))

我想将它转化成这样的元组的列表:

[(159.5,534.5)(157.5,535.5)(157.5,554.5)(155.5,557.5), ...]

谢谢

+2

什么你有没有尝试过?如果你还没有,至少可以给它一点时间 - 你会学到的不仅仅是要求解决方案。 – 2013-03-22 03:35:25

+0

http://stackoverflow.com/questions/3945856/converting-string-to-tuple-and-adding-to-tuple – 2013-03-22 03:35:26

回答

2

就像一个选项,你可以试试这个:

data = "POLYGON ((159.5 534.5, 157.5 535.5, 157.5 554.5, 155.5 557.5))" 
print [tuple(map(float, x.split())) for x in data.replace('POLYGON ((', '').replace('))', '').strip().split(', ')] 

或者没有列表理解:

data = data.replace('POLYGON ((', '').replace('))', '').strip() 
res = [] 
for rec in data.split(', '): 
    res.append(tuple(float(val) for val in rec.split())) 
+0

这一个工作正常 – 2013-03-22 03:53:47

2
>>> re.findall(r'([\d\.]+)\s([\d\.]+)', the_string) 
[('159.5', '534.5'), ('157.5', '535.5'), ('157.5', '554.5'), ('155.5', '557.5')] 

然后,只需将每个项目浮动