gpt4 book ai didi

python - 停止迭代识别可迭代对象

转载 作者:行者123 更新时间:2023-11-28 20:48:57 24 4
gpt4 key购买 nike

我有 2 个生成器并使用下一个方法和 while 循环来处理它,如下所示,

代码

while end_of_loop = 'n':
try:
table1_row = next(table1_generator)
table2_row = next(table2_generator)
except StopIteration:
end_of_loop = 'y'

如何识别哪个迭代器对象没有行?

我正在尝试比较 2 个表,每个表的行都在生成器对象中。

def _compare(self):
end_of_table = 'N'

try:
while end_of_table =='N':
try:
if self.table1_key == self.table2_key:
print 'same key'
self.table1_row = next(self.table1_generator)
self._convert_table1_key_fields()
self.table2_row = next(self.table2_generator)
self._convert_table2_key_fields()
elif self.table1_key > self.table2_key:
self.table2_row = next(self.table1_generator)
self._convert_table2_key_fields()
elif self.table1_key < self.table2_key:
self.table1_row = next(self.table2_generator)
self._convert_table1_key_fields()
except StopIteration as e:
print e.args
print 'IterError'
end_of_table = 'y'

except StopIteration:
print 'Next Iteration'

最佳答案

您可以为 next 提供第二个“sentinel”值:

sentinel = object()
while end_of_loop = 'n':

table1_row = next(table1_generator,sentinel)
table2_row = next(table2_generator,sentinel)

#I don't account for the case where they could be exhausted at
#the same time. It's easy to add that if it matters though.
if table1_row is sentinel:
print "table1_generator gave up first"
#"break" might be more appropriate ...
#(Unless there more to the loop than this.)
end_of_loop = 'y'
elif table2_row is sentinel:
print "table2_generator gave up first"
end_of_loop = 'y'

关于python - 停止迭代识别可迭代对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15773358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com