代码之家  ›  专栏  ›  技术社区  ›  fmark

更多的蟒蛇式迭代方式

  •  3
  • fmark  · 技术社区  · 14 年前

    我使用的模块是商业软件API的一部分。好消息是有一个python模块——坏消息是它非常不完美。

    要对行进行迭代,使用以下语法:

    cursor = gp.getcursor(table)
    row =  cursor.next()
    while row:
        #do something with row
        row = cursor.next()
    

    对付这种情况最要紧的方法是什么?我考虑过创建一个第一类函数/生成器,并在其中包装对for循环的调用:

    def cursor_iterator(cursor):
        row =  cursor.next()
        while row:
            yield row
            row = cursor.next()
    
    [...]
    
    cursor = gp.getcursor(table)
    for row in cursor_iterator(cursor):
        # do something with row
    

    这是一个进步,但感觉有点笨拙。有没有更多的蟒蛇疗法?我应该围绕 table 类型?

    3 回复  |  直到 14 年前
        1
  •  11
  •   user97370    14 年前

    假设next和next中的一个是打字错误,并且它们都是相同的,那么您可以使用内置ITER函数的不太知名的变体:

    for row in iter(cursor.next, None):
        <do something>
    
        2
  •  2
  •   Felix Kling    14 年前

    您可以创建一个自定义包装,如:

    class Table(object):
        def __init__(self, gp, table):
            self.gp = gp
            self.table = table
            self.cursor = None
    
       def __iter__(self):
            self.cursor = self.gp.getcursor(self.table)
            return self
    
       def next(self):
            n = self.cursor.next()
            if not n:
                 raise StopIteration()
            return n
    

    然后:

    for row in Table(gp, table)
    

    参见: Iterator Types

        3
  •  1
  •   Olivier Verdier    14 年前

    最好的方法是在 table 对象,IMHO:

    class Table(object):
        def __init__(self, table):
             self.table = table
    
        def rows(self):
            cursor = gp.get_cursor(self.table)
            row =  cursor.Next()
            while row:
                yield row
                row = cursor.next()
    

    现在您只需打电话:

    my_table = Table(t)
    for row in my_table.rows():
         # do stuff with row
    

    在我看来,它可读性很强。