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

时间:2016-05-25 06:58:20

标签: python scikit-learn decision-tree

所以这是我正在使用的代码:

    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,并在main函数中使用它,使用此代码我遇到此错误:

  

本地变量&#39; output_res&#39;在分配前引用

更新

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

            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 个答案:

答案 0 :(得分:4)

您需要将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)

答案 1 :(得分:3)

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

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

答案 2 :(得分:2)

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

之外
output_res = ""

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