Python遍历Geojson数据坐标应用问题,pythongeojson,有一大推geojson数


有一大推geojson数据,现在需要对其进行坐标转换,geojson数据示例

coordinates = [119,35]coordinates = [[119,35],[119,35]]coordinates = [[[119,35],[119,35]],[[119,35],[119,35]]]

期望转换后的坐标:

coordinates = [11900,3500]coordinates = [[11900,3500],[11900,3500]]coordinates = [[[11900,3500],[11900,3500]],[[11900,3500],[11900,3500]]]

怎么遍历到每一个position(坐标对)?

我现在是这么做的:

def transform(x,y,other_parameter):    return ....def miterator(ary,mapper):    if isinstance(ary,list):        if isinstance(ary[0],list):            for el in ary:                miterator(el, mapper)        else:            ary[0],ary[1] = mapper(ary[0],ary[1])def logic(...):    other_parameter= ....    coordinates = get_coordinates(..)    miterator(coordinates,transform) #??????

然后问题就出来了,我怎么把other_parameter传到transform里面?


所以 我希望最好通过generator方式:

def xgenerator(ary):    if xx:        ...    yield(x,y)

然后我就可以通过这种方式调用:

def logic(...):    other_parameter= ....    coordinates = get_coordinates(..)    for x,y in xgenerator(coordinates):        transform(x,y,other_parameter)

但是这个generator我死活写不出来,怎么破?

这样?

#!/usr/bin/env python3def convert(L):  ret = []  for x in L:    if isinstance(x, (int, float)):      ret.append(x * 100)    else:      ret.append(convert(x))  return retif __name__ == '__main__':  a = [119,35]  b = [[119,35],[119,35]]  c = [[[119,35],[119,35]],[[119,35],[119,35]]]  print(convert(a))  print(convert(b))  print(convert(c))

把坐标一个个地 yield 出来的版本:

def convert(L):  if isinstance(L[0], (int, float)):    yield L  else:    for x in L:      yield from convert(x)

Python 3.2 及以下:

def convert(L):  if isinstance(L[0], (int, float)):    yield L  else:    for x in L:      for y in convert(x):        yield y

这个递归很难写?不过估计Python除了递归应该有更好的方法吧,我也不太懂。顺带帮你把所有的坐标从序列改成元组格式了。仅供参考:

#!/usr/bin/env python3def transform(el, args):    return (el[0]*args[0], el[1]*args[0])def miterator(arrs, mapper, *args):    if isinstance(arrs[0],int):        return mapper(arrs, args[0])    arr = [];    for el in arrs:        if isinstance(el[0], int): item = mapper(el, args[0])        else: item = miterator(el, mapper, args)        arr.append(item)    return arrcoordinates = [[[119,35],[119,35]],[[119,35],[119,35]]]print(miterator(coordinates, transform, 100))# [[(11900, 3500), (11900, 3500)], [(11900, 3500), (11900, 3500)]]

很早之前在OSC上留过一个

def dft(tree):        try:                for c in tree:                        for e in dft(c):                                yield e        except TypeError:                pass        yield tree

http://www.oschina.net/code/snippet_724613_13019

编橙之家文章,

评论关闭