使用列表压缩创建嵌套的`dict`

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

我如何创建一个嵌套的

dict
---列表理解将不胜感激---事件多边形顶点。像这样的东西:

dict = {polygon name :{ vertex: list of incident attributes i.e.: grnd, rf, ot}}

polys = gpd.GeoSeries([Polygon([(0,0), (2,0), (2, 1.5), (2,2), (0,2)]),
                     Polygon([(0,2), (2,2), (2,4), (0,4)]),
                     Polygon([(2,0), (5,0), (5,1.5), (2,1.5)]),
                     Polygon([(3,3), (5,3), (5,5), (3,5)]),
                       Polygon([(6,1), (8, 1), (8, 3), (6, 3)], 
                                     [[(6.5, 1.5), (7.5, 1.5), (7.5, 2.5), (6.5, 2.5)][::-1]]
                                            )])

fp = gpd.GeoDataFrame({'geometry': polys, 'name': ['a', 'b', 'c', 'd', 'e'],
                      'grnd': [25, 25, 25, 25, 25],
                      'rf': [29, 35, 26, 31, 28],
                      'ot': [np.nan, 31, 29, 32, 30]})

fig, ax = plt.subplots(figsize=(6, 6))
fp.plot(ax=ax, alpha=0.3, cmap='tab10', edgecolor='k',)
fp.apply(lambda x: ax.annotate(text=x['name'], xy=x.geometry.centroid.coords[0], ha='center'), axis=1)
plt.show()

我可以创建一个常规

dict
.

dict_vertices = {}
cols = [c for c in ['grnd', 'ot', 'rf'] if c in fp.columns]

for i, row in fp.iterrows():
    oring = list(row.geometry.exterior.coords)#, row['ground_height']
    if row.geometry.exterior.is_ccw == False:
        #-- to get proper orientation of the normals
        oring.reverse() 
    for (j, v) in enumerate(oring[:-1]):
        vertex = (oring[j][0], oring[j][1])
        pol_name = [row['grnd'], row['rf'], row['ot']]
        if vertex in dict_vertices.keys():
            dict_vertices[vertex].append(pol_name)
        else:
            dict_vertices[vertex] = [pol_name]
dict_vertices

`{(0.0, 0.0): [[25, 29, nan]],
 (2.0, 0.0): [[25, 29, nan], [25, 26, 29.0]],
 (2.0, 1.5): [[25, 29, nan], [25, 26, 29.0]],
 (2.0, 2.0): [[25, 29, nan], [25, 35, 31.0]],
 (0.0, 2.0): [[25, 29, nan], [25, 35, 31.0]],
 (2.0, 4.0): [[25, 35, 31.0]],
 (0.0, 4.0): [[25, 35, 31.0]],
 (5.0, 0.0): [[25, 26, 29.0]],
 (5.0, 1.5): [[25, 26, 29.0]],
 (3.0, 3.0): [[25, 31, 32.0]],
 (5.0, 3.0): [[25, 31, 32.0]],
 (5.0, 5.0): [[25, 31, 32.0]],
 (3.0, 5.0): [[25, 31, 32.0]],
 (6.0, 1.0): [[25, 28, 30.0]],
 (8.0, 1.0): [[25, 28, 30.0]],
 (8.0, 3.0): [[25, 28, 30.0]],
 (6.0, 3.0): [[25, 28, 30.0]]}

...但这不是我想要的。我要

dict = {polygon name :{ vertex: incident attributes i.e.: grnd, rf, ot}}
.
理解一些顶点,common/incident属性会重复。 ---列表理解将不胜感激。

python dictionary polygon geopandas vertices
© www.soinside.com 2019 - 2024. All rights reserved.