开发者社区> 问答> 正文

单一比嵌套更好:如何处理深层嵌套的字典?

在作为工程师(而非软件)的工作中,有时我必须使用Python进行编程。在学习了这些教程之后,我了解了字典以及它们如何用于存储数据,快速等。

我嵌套的字典可以达到7个级别,如下所示:

mydict['level1']['level2']['level3']['level4']['level5']['level6']['level7']

我有这些小怪兽,是因为我解析了一个包含如下内容的库的文档:

components['comp1']['comp_name']
components['comp1']['comp_dimension']
components['comp1']['subcomponents']['subcomp1']
components['comp1']['subcomponents']['subcomp1']['comp_name1']
etc.

我还有其他深深嵌套的字典。

我面临的问题是,由于我事先不知道键,因此需要迭代到最后一个级别来获取和过滤结果,所以我像下面的伪代码一样进行迭代:

示例1:漂亮的 filter_subcomps = ["comp1", "comp10"] filter_value = 10.0

for component in components
    comp_name = components[component]['comp_name']
    comp_dimension = components[component]['comp_dimension']
    if components[component].get('subcomponents', False):
        subcomp_keys = filter_subcomps if filter_subcomps else components[component]['subcomponents'].keys()
        for subcomponent in subcomp_keys:
            etc etc
            if value > X:
                return value

示例2:有点难看(下降3级,还有4级...): # I changed the variable names and cut somethings to give a shorter example. # So there probably are some errors that you should ignore. # The goal is to show the ugliness of my code :)

    def get_peak_xy_position(self):
        peak_final_lst = list()
        x_coord_list = list()
        y_coord_list = list()

        filter_comp = self.params['options']['filter_comp']
        filter_comp_parent = self.params['options']['comp_parent']
        filter_peak = self.params['options']['filter_peak']

        for xy_coord in self.xy:
            peak_xy_list = [0]
            x_coord = float(xy_coord.split('_')[0])
            y_coord = float(xy_coord.split('_')[1])

            if self.components.get(xy_coord, False):
                comp_keys = filter_comp if filter_comp else self.components[xy_coord].keys()
                for comp in comp_keys:
                    if self.components[xy_coord].get(comp, False):
                        if self.components[xy_coord][comp].get('comp_parents', False):
                            comp_parent_keys = filter_comp_parent if filter_comp_parent else self.components[xy_coord][comp]['comp_parents'].keys()
                            for parent in comp_parent_keys:
                                if self.components[xy_coord][comp]['comp_parents'][parent].get('comp_signal', False):
                                    peak_signal = self.components[xy_coord][comp]['comp_parents'][parent]['comp_signal']['peak']
                                    final_peak = current_peak_signal
                                    if filter_peak:
                                        final_peak = current_peak_signal if filter_peak <= current_peak_signal else 0
                                    peak_xy_list.append(final_current)
            peak_final_lst.append(max(peak_final_lst))
            x_coord_list.append(x_coord)
            y_coord_list.append(y_coord)

        return x_coord_list, y_coord_list, peak_final_list

这些是一个非常简单的示例,有时代码会进入10多个缩进级别,这看起来很糟糕,我不得不水平滚动页面。除此之外,即使几天或几周后我也很难阅读代码。

我从一些人那里读了一些教程,这些人将列表数据转换为嵌套字典,反之亦然,甚至还使用xpath访问字典键的人们。

无论如何,遵循zen的python,我当然不尊重“扁平比嵌套更好”,因为我的代码进入了缩进的天文水平。

我正在考虑将所有嵌套的dict转换为SQLite并使用SQL语言而不是这些难看的for循环和if条件进行查询。所以我该怎么做?如何处理Python中的嵌套字典,同时保持代码尽可能平坦?我在这里迷路了。

PS:我的问题与“单一比嵌套更好”没有关系-对于数据和代码?因为我已经深深地嵌套了字典。我想知道如何处理这些字典,查询/过滤器值等,同时要有一个固定的代码。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 23:27:40 874 0
1 条回答
写回答
取消 提交回答
  • 有几种解决该问题的方法:

    1. Flatten the structure. If you presume that processing of the flat table will work faster, it might make sense to flatten your structure into the plain list of class or struct instances, and then process the plain list.
    2. If the structure is uniform across levels (even if the names are different on each level), you can use simple recursion. You would have the function which will check if the item on certain level has children, and call itself with each of those children if they are present, or call the data processing function for the final level entries. If subcomponent names differ, you can have an array of such names that would say "on level 1 the items are called 'comp*, on level 2 - 'subcomp* and so on.
    3. If levels require completely different handling, introduce separate functions for each level.

    回答来源:stackoverflow

    2020-03-24 23:27:49
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
继承与功能组合 立即下载
为并行图数据处理提供高层抽象/语言 立即下载
数据+算法定义新世界 立即下载