【问题标题】:Getting next item from generator fails从生成器获取下一个项目失败
【发布时间】:2018-12-13 08:56:49
【问题描述】:

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

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

【问题讨论】:

标签: python python-3.x generator


【解决方案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() 更好。

【讨论】:

  • 使用next()不仅更好,而且必须
  • 你可以使用.__next__()——它就是这样重命名的。但最好选择next()
  • 好的,我也补充一下。
【解决方案2】:

你需要使用:

next(inf_data_gen)

而不是:

inf_data_gen.next()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    • 2020-09-12
    • 2014-04-26
    • 1970-01-01
    相关资源
    最近更新 更多