【发布时间】: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