确定可迭代对象的停止

时间:2013-04-02 20:06:03

标签: python

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

3 个答案:

答案 0 :(得分: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'

答案 1 :(得分:2)

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

答案 2 :(得分: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'