从生成器获取下一项失败

时间:2018-07-04 23:32:22

标签: python python-3.x generator

有一个代码段。运行程序会出现以下错误

epoch, step, d_train_feed_dict, g_train_feed_dict = inf_data_gen.next()
AttributeError: 'generator' object has no attribute 'next'

相应的代码段如下所列。可能是什么原因呢?

inf_data_gen = self.inf_get_next_batch(config)

def inf_get_next_batch(self, config):
        """Loop through batches for infinite epoches.
        """
        if config.dataset == 'mnist':
            num_batches = min(len(self.data_X), config.train_size) // config.batch_size
        else:
            self.data = glob(os.path.join("./data", config.dataset, self.input_fname_pattern))
            num_batches = min(len(self.data), config.train_size) // config.batch_size

        epoch = 0
        while True:
            epoch += 1
            for (step, d_train_feed_dict, g_train_feed_dict) in \
                    self.get_next_batch_one_epoch(num_batches, config):
                yield epoch, step, d_train_feed_dict, g_train_feed_dict

2 个答案:

答案 0 :(得分:1)

您需要使用:

next(inf_data_gen)

而不是:

inf_data_gen.next()

Python 3取消了.next(),将其重命名为.__next__(),但是最好使用next(generator)

答案 1 :(得分:1)

尝试一下:

epoch, step, d_train_feed_dict, g_train_feed_dict = next(inf_data_gen)

查看此内容:there's no next() function in a yield generator in python 3

在Python 3中,需要使用next()而不是.next()

由狄龙·戴维斯(Dillon Davis)建议:您也可以使用.__next__(),尽管.next()更好。