未引用的局部变量?但我可以将它打印好

Chr*_*ett 0 python slice

对于我的生活,我不明白为什么我得到这个错误:

UnboundLocalError: local variable 'unsorted' referenced before assignment (while len(unsorted) > 0)
Run Code Online (Sandbox Code Playgroud)

对于这段代码,我也知道它不是选择排序的最佳实现:

def selection_sort(arr):
    unsorted = arr[:]
    sorted_arr = []
    while len(unsorted) > 0:
        lowest = arr[0]
        lowest_index = 0
        for i in range(len(unsorted)):
            if arr[i] < lowest:
                lowest = arr[i]
                lowest_index = i

        sorted_arr.append(lowest)
        del(unsorted, lowest_index)
    return sorted_arr
Run Code Online (Sandbox Code Playgroud)

Gui*_*ume 7

您收到此错误的原因是:

del(unsorted, lowest_index)
Run Code Online (Sandbox Code Playgroud)

删除这两个变量unsortedlowest_index,然后在你的下一个循环反过来,你要再次使用它们.