在 for 循环中添加元素时覆盖集合元素

Collection element is overridden while adding elements in for loop

我有一个 geojson,其中可能有多边形或多边形类型的要素。如果它是多边形,我想将它分解成多边形。

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

例如以上 geojson 应该创建 2 个工作正常的功能,但我也想为每个功能生成唯一的 id,我正在使用 str(uuid.uuid4())。这为每个 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)

问题出在'properties': feature['properties']

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

你必须克隆它。

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