阻止Python For循环覆盖字典

问题描述 投票:0回答:1

我正在尝试创建一个新的字典(intersections),它包含一个名为zones的字典中多边形的交叉区域。

我使用combinations找到所有可能的zones独特组合。然后我使用Shapely的.intersects()测试区域相交的if。如果他们这样做,我希望他们的几何保存在变量int_geometry中,然后存储在字典中(使用:Shapely的.intersection())。

我知道有四个交叉点,因为这段代码返回它们:

for a, b in combinations(zones.values(), 2):
  a_geom = a['location']
  b_geom = b['location']
  if a_geom.intersects(b_geom) == True:
    print a_geom.intersection(b_geom)

但是,如果我替换if语句之后的内容,如下面的代码所示,它会开始覆盖自己。

intersections = {}    

for a, b in combinations(zones.values(), 2):
  a_geom = a['location']  
  b_geom = b['location']  
  if a_geom.intersects(b_geom) == True:
    int_geometry = a_geom.intersection(b_geom)
    int_area = round(int_geometry.area,2)
    int_perimeter = round(int_geometry.length,2)
    intersections = {
      'geometry' : int_geometry,
      'attributes' : {
        'area' : int_area,
        'perimeter' : int_perimeter,
      }
    }    

pprint(intersections)

关于类似问题有多个主题,但我找不到答案。我知道我忽略了一些非常明显的东西,但我无法察觉。有人可以向我解释我做错了什么吗?

python dictionary for-loop gis overwrite
1个回答
1
投票

index中的int_index = "int_index " + str(index + 1)将始终与第一个循环后的值相同,它的值是常数。因此数据被覆盖。

...

# PART 2 - ANALYSE THE DATA
intersections = {}
index = 0

for a, b in combinations(zones.values(), 2):
  a_geom = a['location']
  b_geom = b['location']
  if a_geom.intersects(b_geom) == True:
    int_index = "int_index " + str(index + 1)
    int_geometry = a_geom.intersection(b_geom)
    int_area = round((a_geom.intersection(b_geom).area),2)
    int_perimeter = round((a_geom.intersection(b_geom).length),2)
    intersections[int_index] = {
      'geometry' : int_geometry,
      'attributes' : {
        'area' : int_area,
        'perimeter' : int_perimeter,
      }
    }
    index += 1

pprint(intersections)
© www.soinside.com 2019 - 2024. All rights reserved.