遍历复杂的嵌套字典

时间:2019-11-25 16:01:59

标签: python dictionary

我有一个非常复杂的字典列表,其中包含嵌套字典和数组。我正在尝试找到一种解决方法,

  1. 使数据列表更简单,然后遍历 栅格点或
  2. 找到一种原样遍历栅格点阵列的方法。

我最终想要做的是遍历每个面内的所有栅格点,对分配给该栅格点的值执行简单的大于或小于该值(值是高程值)的操作。如果大于给定值,则赋值为1;如果小于给定值,则赋值为0。然后,我将创建一个分别包含这些1和0的数组,然后我可以得到一个平均值。

我已经找到了所有这些点(pts中的所有点),但是它们至少在列表中(所有多边形的列表中)另一个字典中的字典数组中,我认为,在组织中我可能是错的,因为字典是对我来说是新的。

以下是我的代码:

import numpy as np

def mystat(x):

    mystat = dict()
    mystat['allpoints'] = x
    return mystat

stats = zonal_stats('acp.shp','myGeoTIFF.tif')

pts = zonal_stats('acp.shp','myGeoTIFF.tif', add_stats={'mystat':mystat})

Link到我的文档。任何帮助或指示将不胜感激!

1 个答案:

答案 0 :(得分:0)

我认为您正在使用rasterstats软件包。您可以尝试这样的事情:

threshold_value = 15  # You may change this threshold value to yours

for o_idx in range(0, len(pts)):
    data = pts[o_idx]['mystat']['allpoints'].data
    for d_idx in range(0, len(data)):
        for p_idx in range(0, len(data[d_idx])):
            # You may change the conditions below as you want
            if data[d_idx][p_idx] > threshold_value:
                data[d_idx][p_idx] = 1
            elif data[d_idx][p_idx] <= threshold_value:
                data[d_idx][p_idx] = 0;

它将更新pts列表中的数据