gpt4 book ai didi

python - 赋值前引用的局部变量

转载 作者:太空狗 更新时间:2023-10-30 01:57:11 25 4
gpt4 key购买 nike

我是 python 的新手,我找到了这个问题的一些答案,但没有什么能真正帮助我。

这是我遇到问题的部分代码:

batch_index=0 # initializing a globale variable, I've tried with global batch_index too 
..................................

def next_Training_Batch():
if batch_index < len(train_data):
batch_index = batch_index + 1
return train_data[batch_index-1], train_labels[batch_index-1]
else :
shuffle_data()
batch_index = 0
return train_data[batch_index], train_labels[batch_index]

当我调用该函数时,我得到以下信息:

UnboundLocalError: local variable 'batch_index' referenced before assignment

我不想在函数中使用参数(如类似问题中所建议的那样)并且老实说我正在使用“全局”变量的数量而没有任何错误,我不明白为什么我不允许在 if 语句中评估它?感谢您的任何提示!

最佳答案

global batch_index 添加到函数的开头,它会知道您指的是全局变量而不是局部变量。

batch_index=0 # initializing a globale variable, I've tried with global batch_index too 
...

def next_Training_Batch():
global batch_index
if batch_index < len(train_data):
batch_index = batch_index + 1
return train_data[batch_index - 1], train_labels[batch_index - 1]
else:
shuffle_data()
batch_index = 0
return tain_data[batch_index], train_labels[batch_index]

关于python - 赋值前引用的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43606981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com