从字符串创建元组列表 (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 个回答
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')]
然后只需要把每个项目转换成浮点数就可以了。
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()))