【问题标题】:Prevent Python For Loop from overwriting dictionary防止 Python For 循环覆盖字典
【发布时间】:2019-02-13 12:18:12
【问题描述】:

我正在尝试创建一个新字典 (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)

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

【问题讨论】:

  • 您在 for 循环的每次迭代中将名称 intersections 重新分配给新字典。 (您在右侧构建的那个。)很难说更多,因为您的代码不是自包含的(我们无法复制粘贴并运行它)并且最终期望的结果尚不清楚。
  • 你可能想要像 intersections[geometry] = { 'geometry' : int_geometry, 'attributes' : { 'area' : int_area, 'perimeter' : int_perimeter, } } 这样的东西。

标签: python dictionary for-loop gis overwrite


【解决方案1】:

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

...

# 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)

【讨论】:

  • 是的,我想存储数据,就像在您的第一个示例中一样,我知道如何将数据存储在列表中,但我想将其存储在字典中。我刚刚在上面添加了我的完整代码。如您所见,我(认为我)使用完全相同的结构来创建zones 字典。而且效果很好。
  • index in int_index = "int_index " + str(index + 1) 将始终与第一次循环后的值相同,它的值是恒定的。因此覆盖。
猜你喜欢
  • 1970-01-01
  • 2017-12-25
  • 2016-01-16
  • 2018-11-21
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
相关资源
最近更新 更多