我的生成器(batch_generator)返回了5个值,但我似乎无法弄清楚如何遍历这些值。
我尝试过的事情:
1)直接在for循环定义(ValueError: too many values to unpack (expected 5))中解压缩
for a, b, c, d, e in next(batch_generator):
# do something with a-e
Run Code Online (Sandbox Code Playgroud)
2)在for循环ValueError: too many values to unpack (expected 5)中解包(在我解包的行item)
for item in next(batch_generator):
a, b, c, d, e = item
# do stuff
Run Code Online (Sandbox Code Playgroud)
3)将其压缩并解压缩for循环定义(ValueError: not enough values to unpack (expected 5, got 1))
for a, b, c, d, e in zip(next(batch_generator)):
# do stuff
Run Code Online (Sandbox Code Playgroud)
4)将其压缩并在for循环中解压缩(ValueError: not enough values to unpack (expected 5, got 1)在我解压缩的那一行中item,我认为它现在已经包装在另一个元组中)
for item in zip(next(batch_generator)):
a, b, c, d, e = item
Run Code Online (Sandbox Code Playgroud)
关于元组/生成器实际发生的任何解释,将不胜感激!
我的收益声明看起来像
yield a, b, c, d, e
根据该评论,生成器似乎发出5元组的序列。
然后,您可以简单地使用:
for a, b, c, d, e in batch_generator:
# ^ no next(..)
pass
Run Code Online (Sandbox Code Playgroud)
因此,您不应使用next(..)。next简单地返回nextyield。现在,由于那是一个元组,因此for循环将遍历该元组,而不是生成器。
该for循环将迭代生成器batch_generator发出的元组,直到生成器用尽为止(或者循环中有一个break/ return语句for被激活。
请注意,for循环的工作方式如下:
for <pattern> in <expression>:
# ...
Run Code Online (Sandbox Code Playgroud)
本<expression>应该是一个迭代(发电机,元组,列表,...)和<pattern>用于分配给。如果遍历元组,那么就遍历该元组的元素,而不是遍历完整的元组。
| 归档时间: |
|
| 查看次数: |
1071 次 |
| 最近记录: |