0
#!/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程序,它發生在具有嵌套列表的文本文件並計算列表中每個級別的項目數和將這些值作爲打印語句輸出。我已經使用遞歸編寫上述代碼,但我有麻煩,下面的錯誤運行:試圖賦值之前引用一個遞歸函數裏面的變量
UnboundLocalError: local variable 'index' referenced before assignment
我的理解是,在函數內部的指數是指數變量我在底部初始化的範圍之內。任何幫助解決這個代碼或啓動並運行將不勝感激。
感謝解決了這個問題,但只是爲了澄清當我在函數中使用全局變量時,我是否每次都必須編寫全局變量?因爲現在我看到了錯誤:NameError:全局名稱'index'沒有在行中定義Counts [index] = Counts [index] + 1 –
@AmmarAhmad我添加了一個鏈接來解決這個問題。規則是,如果你指定它,除非另有說明,Python假定它是一個本地。這就是說,這個錯誤很奇怪。我希望這個錯誤在'Counts'上。每個功能只需要說明一次。 –