【问题标题】:Collection element is overridden while adding elements in for loop在 for 循环中添加元素时,集合元素被覆盖
【发布时间】:2020-11-23 21:22:05
【问题描述】:

我有一个geojson,其中可能包含多多边形或多边形类型的特征。如果它是多多边形,我想将其分解为多边形。

{
     "type": "FeatureCollection",
     "features": [
         {
             "type": "Feature",
             "properties": {
                 "id": "86aba1ae-80e2-49d4-ab32-c2744a3b4bf4"
             },
             "geometry": {
                 "type": "MultiPolygon",
                 "coordinates": [
                     [...],
                     [...]
                 ]
             }
         }
      ]
}

例如以上geojson 应该创建2 个工作正常的功能,但我还想为每个我正在使用str(uuid.uuid4()) 的功能生成唯一的id。这为每个 xfeature 提供了唯一的 id,但是当它附加到 output 集合时,第二个总是覆盖第一个并且 id 是重复的。我找不到发生这种情况的原因以及如何解决它。

js = open('test.geojson', 'r').read()
gj = json.loads(js)

output = {"type": "FeatureCollection", "features": []}

for feature in gj['features']:
    if ((feature['geometry'] is not None) 
        and (feature['geometry']['type'] == 'MultiPolygon')):
        for poly in feature['geometry']['coordinates']:
            xfeature = {"type": "Feature", 'properties': feature['properties'], 
                        "geometry": {"type": "Polygon"}}
            xfeature['properties']['id'] = str(uuid.uuid4())
            xfeature['geometry']['coordinates'] = poly
            output['features'].append(xfeature)
    else:
        output['features'].append(feature)

【问题讨论】:

    标签: python json geojson


    【解决方案1】:

    问题是'properties': feature['properties']在行

        xfeature = {"type": "Feature", 'properties': feature['properties'], "geometry": {"type": "Polygon"}}
    

    你必须克隆它。

    使用 deepcopy 来做到这一点 - https://docs.python.org/3/library/copy.html

    【讨论】:

      猜你喜欢
      • 2020-03-20
      • 1970-01-01
      • 2022-07-29
      • 2018-03-15
      • 2020-08-28
      • 2022-12-18
      • 2011-02-16
      • 2021-12-15
      • 2018-05-18
      相关资源
      最近更新 更多