尝试在递归函数内赋值之前引用变量

时间:2017-09-26 17:35:28

标签: python-2.7 recursion

#!/usr/bin/python

import sys


def Count_Totals(lst):       # returns an array with the number of elements in each level on nesting
    for el in lst:
            if type(el)==list:
                    temp=el
                    index = index + 1       # this is index of Counts which indicates the level of nesting
                    Count_Totals(el)
            else:
                    Counts[index] = Counts[index] + 1               # When we reach the bottom nest to count elements
                    Size = Size + 1

                    if Size == len(temp) - 1:
                            index = index - 1 # When list inside list runs out of elements

in_file = sys.argv[1]
with open(in_file,'r') as input_file:
        lines = input_file.readlines()            # reads entire ascii file and 
saves into a list called lines

Frame = 0
Size = 0
index = 0

for line in lines:                                # creates a list of each row in text file
        Counts = []
        Frame = Frame + 1
        Count_Totals(line)                       #Counts the elements in each level of nest

print("The Frame contains: %d subrames, which is %d Symbols", Count[0] , Count [1])

您好,我正在尝试编写一个python 2.7程序,该程序接收具有嵌套列表的文本文件,并计算每个列表级别中的项目数,并将这些值输出为print语句。我已经使用递归编写了上面的代码,但是我遇到以下错误时遇到了问题:

UnboundLocalError: local variable 'index' referenced before assignment

我的理解是函数内部的索引超出了我在底部初始化的索引变量的范围。任何帮助修复此代码或启动并运行它将非常感激。

1 个答案:

答案 0 :(得分:0)

在我看来,您不想访问名为index的本地变量。您想要访问名为0的全局,这是您稍后初始化为global的内容。

当python第一次看到函数中使用的变量时,它必须弄清楚你是想要它是全局变量还是本地变量。它本身就是错误的。特别是,如果您指定该值,则假定它是本地的(确切的规则是findOneAndReplace())。

要解决此问题,您只需在函数中添加def Count_Totals(lst): global index for el in lst: 语句即可。这告诉Python指定的变量实际上是全局变量。

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\PrivateAssemblies\Microsoft.VisualStudio.Setup.Engine.dll