Skip to main content
 首页 » 编程设计

python之在每第二次出现未知元素后拆分字符串

2025年05月04日27小虾米

我有一个字符串,其中包含代表多边形的坐标列表。 在这个列表中,每个多边形都有相同的起始和结束坐标。 我需要将每个多边形放在单独的字符串(或列表)中。

'17.17165756225586 -28.102264404296875,17.184370040893555 -28.200496673583984,17.1986083984375 -28.22361373901365728165 -28.2236137390136517.81655 -2655 28.102264404296875, 28.865726470947266 -28.761619567871094,28.80694007873535 -28.75750160217285,28.792499542236328 -28.706947326660156,2827.8765 61619567871094

所以从这个简单的例子我需要有两个元素:

One = '17.17165756225586 -28.102264404296875,17.184370040893555 -28.200496673583984,17.1986083984375 -28.223613739013677.816515 -28.223613739013677.816515 -26515 28.102264404296875'

两个='28.865726470947266 -28.761619567871094,28.80694007873535 -28.75750160217285,28.792499542236328 -28.706947326660502236328 -28.7069473266601564,7 66 -28.761619567871094'*

字符串中可以有更多的多边形,每个多边形都需要分开。 为此,我只能使用标准的 Python 库

请您参考如下方法:

s='17.17165756225586 -28.102264404296875,17.184370040893555 -28.200496673583984,17.1986083984375 -28.223613739013672,17.17165756225586 -28.102264404296875, 28.865726470947266 -28.761619567871094,28.80694007873535 -28.75750160217285,28.792499542236328 -28.706947326660156, 28.865726470947266 -28.761619567871094' 
 
#convert the input in a list of points  
coordinates = [tuple(map(float,el.split())) for el in s.split(",")] 
 
polygons = [] 
 
#find the polygons 
while coordinates: 
    ind = coordinates[1:].index(coordinates[0])  
    polygons.append(coordinates[0:ind+2]) 
    coordinates = coordinates[ind+2:] 
 
#output 
[(17.17165756225586, -28.102264404296875), (17.184370040893555, -28.200496673583984), (17.1986083984375, -28.223613739013672), (17.17165756225586, -28.102264404296875)] 
[(28.865726470947266, -28.761619567871094), (28.80694007873535, -28.75750160217285), (28.792499542236328, -28.706947326660156), (28.865726470947266, -28.761619567871094)]