【问题标题】:python recursion avoid result as global variablepython递归避免结果作为全局变量
【发布时间】:2020-04-26 22:52:28
【问题描述】:
res_dict = {}

def get_value(co , passed_dict ):

    for k, v in passed_dict.items():
        if isinstance(v, dict):
            get_value(co, v)
        else:
            res_dict[k] = v
            print("from else",res_dict)

    return res_dict


def easy():

    inner_dict = {
                    "test1" : {"test1_in" : "abc"},
                    "test2" : {"test1_in" : "xyz"}
                  }
    dict1 = {}
    count = 0
    val_from_function= {}
    key_list = ['key1','key2']

    for key in key_list:
        count = count + 1
        val_from_function = get_value(count ,inner_dict)
        print("before assign" ,dict1 )
        dict1[key] = val_from_function
        print("after assign" , dict1)

    # dict1['key1'] = {'test1' : "abc"}
    # dict1['key2'] = {'test1' :  "xyz"}

    print(dict1)

easy() 

  • 接收输出:{'key1': {'test1_in': 'xyz'}, 'key2': {'test1_in': 'xyz'}}
  • 预期 o/p : {'key1': {'test1_in': 'abc'}, 'key2': {'test1_in': 'xyz'}}

  • 我了解 dict1 的值已更新为 res_dict 声明为全局的最后一个值 多变的。

  • 我可以通过将内部键值附加到外部键然后存储在字典中来解决它。
  • 我可能会使用有序字典来解决它。
  • 将列表中的键作为外部键值 (key1, key2 ..,key3000) 未知。

寻找有关如何使用预期的 o/p 使此代码更好的建议。 有 3k 个密钥对值,与具有更多嵌套 k、v 和将 o/p 存储为缓存的示例模式相同,因此这里的性能不是一个很大的问题。

【问题讨论】:

    标签: python-3.x recursion


    【解决方案1】:
    # This modifies passed_dict
    
    
    def get_value(passed_dict, recur_dict_new={}, isInitial=True):
    
        for k, v in passed_dict.items():
            if isInitial:
                recur_dict_new = {}
            if isinstance(v, dict):
                temp = get_value(v, recur_dict_new, isInitial=False)
                passed_dict[k]= temp
            else:
                recur_dict_new[k]=v
    
        return recur_dict_new
    
    
    def easy():
    
        inner_dict = {
                        "test1" : {"test1_in" : "abc"},
                        "test2" : {"test1_in" : "xyz"}
                      }
    
        key_list = ['key1','key2']
    
        for key in key_list:
            get_value(inner_dict)
        # dict1['key1'] = {'test1' : "abc"}
        # dict1['key2'] = {'test1' :  "xyz"}
    
        print(inner_dict)
    
    easy()
    
    

    感谢收看,我已经用上面提到的一种方法解决了, 用 15k 条记录和 3 层以上的嵌套 JSON 测试,性能还可以(4ms)

    • O/p : {'test1': {'test1_in': 'abc'}, 'test2': {'test1_in': 'xyz'}}

    【讨论】:

      猜你喜欢
      • 2022-01-07
      • 2012-12-19
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 2016-01-06
      相关资源
      最近更新 更多