我在编程项目中遇到了一个问题,需要一些帮助……我认为这是一个有趣的问题 :-)
我正在尝试格式化从GeoJSON获取的类似下面的坐标(由于长度很长,我在此处进行了缩短)。
[[[[-1.241956526315958, 54.722452909315834], [-1.242505189342398, 54.72242038994674], [-1.24192061729046, 54.722713302903806], [-1.241956526315958, 54.722452909315834]]], [[[-1.270237428346303, 54.7271584144655], [-1.268210325997062, 54.72608036652354], [-1.267390512992676, 54.726854573664205]]]]
我需要它们最后看起来像这样:
“54.722452909315834,-1.241956526315958:54.72242038994674,-1.242505189342398:54.722713302903806,-1.24192061729046:54.722452909315834,-1.241956526315958:54.7271584144655,-1.270237428346303:54.72608036652354,-1.268210325997062,”
目前我已经按照以下代码运行成功,其中变量poly首先被分配一个坐标块,就像上面发布的第一个代码块那样。
def threetimes(func):
"""Executes the function on its own output two times."""
@functools.wraps(func)
def wrapper_three_times(*args, **kwargs):
value = func(*args, **kwargs)
value2 = func(value)
value3 = func(value2)
return value3
return wrapper_three_times
def swap_pairs(poly):
"""
Turns a list like this [1, 2, 3, 4] into [2, 1, 4, 3]
:param polys: list
:return: list
"""
for i in range(0, len(poly) - 1, 2):
poly[i], poly[i + 1] = poly[i + 1], poly[i]
return poly
@threetimes
def flatten_polys(poly):
"""
Turns geojson polygons into flat lists.
:param poly: List of three lists; standard geojson polygon or multipolygon format.
:return: flat list of the polygon co-ordinates.
"""
flat_poly = [item for sublist in poly for item in sublist]
return flat_poly
poly = flatten_polys(poly)
poly = swap_pairs(poly)
polys_formatted = [str(x) + ',' + str(y) + ':' for x, y in zip(poly[0::2], poly[1::2])]
polys_formatted[-1] = polys_formatted[-1].replace(':', '')
poly_as_string = ''.join(x for x in polys_formatted)
然而问题在于,有时候坐标的子列表数量不同于这个示例中的三个,例如以下这样(为了简洁起见再次缩短):
[[[-0.109373710729991, 51.42315755917108], [-0.105987341539958, 51.422576811743276], [-0.096906133161734, 51.422667109533435], [-0.094346733695295, 51.422818864663064], [-0.092734433338077, 51.42253994327862], [-0.088190383828824, 51.419927269261336], [-0.086425687184976, 51.419305849976176], [-0.082346001337163, 51.419771533877956], [-0.078548643992427, 51.41984782473602], [-0.080993694631571, 51.417101046706534], [-0.080475514860821, 51.415566497757084]]]
所以我认为我需要一个函数,用于展平嵌套的子列表,该函数重复执行 n 次,直到无法执行而不出错...
对于任何帮助,我将非常感激...
-1.241956526315958:54.72242038994674,
。那应该是一个字符串吗? - Mark