我遇到了一个关于 python 中 while true 循环的问题。 代码如下
def batched(iterator, batch_size):
while True:
data = np.zeros(batch_size)
target = np.zeros(batch_size)
for index in range(batch_size):
data[index], target[index] = next(iterator)
yield data, target
batches = batched(examples, params.batch_size)
for index, batch in enumerate(batches):
.......
.......
循环没有break,永远保持true,这个循环怎么可能停止。 附言。代码是《TensorFlow for Machine Intelligence》一书中的示例。
请您参考如下方法:
我正在写这个答案,因为评论部分似乎有点过于狭窄。
首先,阅读有关 Iterators in python 的内容将消除您的困惑。
我会尽力解释的! :D
def batched(iterator, batch_size):
while True:
data = np.zeros(batch_size)
target = np.zeros(batch_size)
for index in range(batch_size):
data[index], target[index] = next(iterator)
yield data, target
batched 是一个生成器/迭代器函数。这里的关键是 yield。当程序流达到 yield 时,函数“返回”值(在我们的例子中为 data, target)。 但要注意的是,仅下次调用该函数时,流程会从上次产生的地方继续。在我们的在这种情况下,下次调用该函数时,循环从头开始。
现在,您可能会被没有 breaking 条件的 while True: 循环误导,batched 不是阻塞函数调用.
另外,请注意,
batches = batched(examples, params.batch_size)
不是函数调用。当你执行上面的行时,你只是得到一个指向迭代器的指针。该函数仅在迭代时运行!
对你来说,它正在这里完成:
for index, batch in enumerate(batches):
在这里,for 循环将陷入无限循环,如果循环中没有处理终止条件。这意味着,需要在 for 循环内使用 break 手动终止循环。
