2

我有 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'
4

3 回答 3

4

您可以提供第二个“哨兵”值next

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'
于 2013-04-02T20:09:37.530 回答
2

您没有提供有关上下文或您实际尝试做的事情的详细信息,但听起来itertools.izip_longest可能对您的情况有用(并且更多pythonic)。您可以填写Nones或其他合适的值。

于 2013-04-02T20:09:11.517 回答
1

我想不出一个用例(愿意分享吗?),但我会尝试包装next到我自己的函数中:

def mynext(it):
    try:
        return next(it)
    except StopIteration:
        raise StopIteration(it)

然后,例如,

a = iter([1,2,3,4,5])
b = iter([4,5,6,7])

try:
    while True:
        print mynext(a)
        print mynext(b)
except StopIteration as e:
    if e.args[0] == a: print 'a ended' 
    if e.args[0] == b: print 'b ended' 
于 2013-04-02T20:19:09.183 回答