代码之家  ›  专栏  ›  技术社区  ›  RoyaumeIX

将串联字符串作为全局变量返回

  •  0
  • RoyaumeIX  · 技术社区  · 8 年前

    下面是我使用的代码:

        global output_res
        output_res = ""
    
        def recurse(left, right, threshold, features, node, depth):
            spacer = spacer_base * depth
            if (threshold[node] != -2):
                """print(spacer + "if ( " + features[node] + " <= " + \
                    str(threshold[node]) + " ) {")"""
                output_res += spacer + "if ( " + features[node] + " <= " + \
                    str(threshold[node]) + " ) {"
                if left[node] != -1:
                    recurse (left, right, threshold, features, left[node], depth+1)
                """print(spacer + "}\n" + spacer +"else {")"""
                output_res += spacer + "}\n" + spacer +"else {"
                if right[node] != -1:
                    recurse (left, right, threshold, features, right[node], depth+1)
                """print(spacer + "}")"""
                output_res += spacer + "}"
            else:
                target = value[node]
                for i, v in zip(np.nonzero(target)[1], target[np.nonzero(target)]):
                    target_name = target_names[i]
                    target_count = int(v)
                    """print(spacer + "return " + str(target_name) + " ( " + \
                        str(target_count) + " examples )")"""
                    output_res += spacer + "return " + str(target_name) + " ( " + \
                        str(target_count) + " examples )"
    
            return output_res
    
        recurse(left, right, threshold, features, 0, 0)
    

    正如你所见 recurse() 是一个递归函数,我的目标是检索 output_res ,并在主函数中使用它,使用此代码时出现以下错误:

    赋值前引用的局部变量“output_res”

    使现代化

    我找到了我想要的确切解决方案:

                temp_list = []
                def recurse(temp_list, left, right, threshold, features, node, depth):
                    spacer = spacer_base * depth
                    if (threshold[node] != -2):
                        temp_list.append(spacer + "if ( " + features[node] + " <= " + \
                            str(threshold[node]) + " ) {")
                        if left[node] != -1:
                                recurse (temp_list, left, right, threshold, features, left[node], depth+1)
                        temp_list.append(spacer + "}\n" + spacer +"else {")
                        if right[node] != -1:
                                recurse (temp_list, left, right, threshold, features, right[node], depth+1)
                        temp_list.append(spacer + "}")
                    else:
                        target = value[node]
                        for i, v in zip(np.nonzero(target)[1], target[np.nonzero(target)]):
                            target_name = target_names[i]
                            target_count = int(v)
                            temp_list.append(spacer + "return " + str(target_name) + " ( " + \
                                str(target_count) + " examples )")
    
                recurse(temp_list, left, right, threshold, features, 0, 0)
                return '\n'.join(temp_list)
    
    3 回复  |  直到 8 年前
        1
  •  4
  •   tfv    8 年前

    你需要把 global 命令导入函数,只需确保预先定义了全局变量:

        output_res = ""
    
        def recurse(left, right, threshold, features, node, depth):
            global output_res
            spacer = spacer_base * depth
            if (threshold[node] != -2):
                """print(spacer + "if ( " + features[node] + " <= " + \
                    str(threshold[node]) + " ) {")"""
                output_res += spacer + "if ( " + features[node] + " <= " + \
                    str(threshold[node]) + " ) {"
                if left[node] != -1:
                    recurse (left, right, threshold, features, left[node], depth+1)
                """print(spacer + "}\n" + spacer +"else {")"""
                output_res += spacer + "}\n" + spacer +"else {"
                if right[node] != -1:
                    recurse (left, right, threshold, features, right[node], depth+1)
                """print(spacer + "}")"""
                output_res += spacer + "}"
            else:
                target = value[node]
                for i, v in zip(np.nonzero(target)[1], target[np.nonzero(target)]):
                    target_name = target_names[i]
                    target_count = int(v)
                    """print(spacer + "return " + str(target_name) + " ( " + \
                        str(target_count) + " examples )")"""
                    output_res += spacer + "return " + str(target_name) + " ( " + \
                        str(target_count) + " examples )"
    
            return 
    
        recurse(left, right, threshold, features, 0, 0)
    
        2
  •  3
  •   Arun G    8 年前

    如果你真的想使用全局变量

    output_res = ""
    
    def recurse(left, right, threshold, features, node, depth):
        global output_res
        //your code
        //no need to do "return output_res"
    
    recurse(left, right, threshold, features, 0, 0)
    

    说明:

    In [8]: myG = 5
    
    In [9]: def fun1():
       ...:     myG=45
       ...: 
    
    In [10]: def fun2():
       ....:     print myG
    
    In [11]: fun1()
    
    In [12]: fun2()
    5 //output
    
    //Now change the fun1 with global
    In [15]: def fun1():
       ....:    global myG
       ....:    myG=45
    
    In [17]: fun1()
    
    In [18]: fun2()
    45 //output, this explains how global affects the scope
    
        3
  •  3
  •   Cal Eliacheff    8 年前

    您需要将全局语句放在函数内部,而不是放在函数外部

    output_res = ""
    
    def recurse(left, right, threshold, features, node, depth):
        global output_res
        ...