下面是我的例子。我尝试将global添加到我想要更改的变量中,但没有帮助。我得到的错误在评论中。
def getNumOfSwapsToSort(array):
sorted = array.copy()
sorted.sort()
swaps = 0
def swap():
currentSwaps = 0
for i, el in enumerate(array):
if ((len(array) - 1) == i) and currentSwaps != 0:
swap()
elif el != sorted[i]:
idx = sorted.index(el)
temp = array[idx]
array[idx] = el
array[i] = temp
# UnboundLocalError: local variable 'swaps' referenced before assignment
# if I use global swaps, then NameError: name 'swaps' is not defined
swaps += 1
currentSwaps += 1
swap()
return swaps发布于 2020-02-17 18:02:15
代码中的swaps变量不是全局变量,而是非本地变量。它是在封闭函数getNumOfSwapsToSort()中定义的,而不是在全局命名空间中定义的。
您的另一个函数swap()可以访问这个非局部变量,但是该变量不受内部函数编辑的影响。如果您试图编辑或覆盖它,它将被视为一个新的局部变量-因此您将得到UnboundLocalError。
尝试使用语句
nonlocal swaps
swaps += 1这里有一篇文章,其中有几个简单的例子来解释Python中的闭包概念。
发布于 2020-02-17 18:00:41
swaps不是全局的,它在getNumOfSwapsToSort中,它是swap的父范围。所以使用nonlocal声明。
def swap():
nonlocal swaps
...https://stackoverflow.com/questions/60267960
复制相似问题