使用过多的迭代和条件优化代码

时间:2017-03-30 15:02:40

标签: python optimization refactoring

我正在尝试在我的应用中优化这段代码,因为我觉得我有太多的条件和嵌套周期(我的机器也是如此)。

这是一个片段:

def some_kind_of_method(data):

    # data is a dict() object

    for key, value in data.viewitems():
        if type(value) is OrderedDict:

            if key == 'something':
                do_method_1(key, value)

                for sub_key, sub_value in value.viewitems():

                    stored_value = do_method_2(sub_key, sub_value)

                    if type(sub_value) is OrderedDict:
                        for sub_key2, sub_value2 in sub_value.viewitems():
                            do_method_3(sub_key2, sub_value2, extra_var=store_value)

                    else:
                        do_method_3(sub_key, sub_value)
            else:
                for sub_key, sub_value in value.viewitems():
                    do_action(sub_key, sub_value)

        elif type(value) is list:
            for lst_item in value:

                do_method_1(key, value)

                for sub_lst_key, sub_lst_value in lst_item.viewitems():
                    do_method_2(sub_lst_key, sub_lst_value)

                    if type(sub_lst_value) is OrderedDict:
                        for sub_key2, sub_value2 in sub_lst_value.viewitems():
                            do_method_3(sub_key2, sub_value2, extra_var=stored_value)

                    else:
                        do_method_3(sub_lst_key, sub_lst_value)

        else:
            do_method_3(key, value)

   return True

对这位仍然是新手开发者的任何建议?

0 个答案:

没有答案