我有以下功能,并且不时返回错误“全局名称'x'未定义”,当它跳转到return语句时会发生。我希望在不失去功能的情况下帮助改进此代码。任何见解将不胜感激。
def label(tree, instance, class_labels):
'''Returns the label at the end of every "branch" in the tree'''
global x
for row in tree:
if row[0] == instance[row[1]]:
if row[2][0] in class_labels:
x = row[2][0]
return x
else:
x = label(row[2], instance, class_labels)
return x
答案 0 :(得分:2)
这可能会有所帮助......
def label(tree, instance, class_labels):
'''Returns the label at the end of every "branch" in the tree'''
last = None
for row in tree:
if row[0] == instance[row[1]]:
if row[2][0] in class_labels:
return row[2][0]
next = label(row[2], instance, class_labels)
if next is not None:
last = next
return last