我有一个形式的字符串:
多边形 ((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), ...]
谢谢
像一个选项,你可以试试这个:
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()))
>>> re.findall(r'([\d\.]+)\s([\d\.]+)', the_string)
[('159.5', '534.5'), ('157.5', '535.5'), ('157.5', '554.5'), ('155.5', '557.5')]
然后只需将每个项目转换为浮动