我是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
我不想在函数中使用参数(如类似问题所示)并且说实话,我使用&#34; global&#34;变量没有任何错误,我不明白为什么我不允许在if语句中对它进行评估? 谢谢你的暗示!
答案 0 :(得分:8)
将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]
答案 1 :(得分:2)
使用创建变量副本的全局关键字
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]
但仍未定义train_data
答案 2 :(得分:0)
在函数中使用全局说全局batch_index
batch_index = 0#初始化全局变量,我也试过全局batch_index
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]