【问题标题】:More pythonic way to iterate更pythonic的迭代方式
【发布时间】:2010-06-05 10:48:42
【问题描述】:

我正在使用作为商业软件 API 一部分的模块。好消息是有一个 python 模块 - 坏消息是它非常不符合 Python 标准。

要遍历行,使用以下语法:

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

处理这种情况最pythonic的方法是什么?我考虑过创建一个一流的函数/生成器并在其中包装对 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 类型创建一个包装类吗?

【问题讨论】:

  • cursor.next() 看起来你可能能够做到for row in cursor:
  • @Felix,不。 next 不会引发 StopIteration,所以在真实数据之后,这将永远循环,rowNone
  • @Felix King:差不多,但是因为迭代器通过引发 StopIteration 发出终止信号,for row in cursor: 将遍历行,然后给出Nones 的无限流。
  • @Matthew, @Paul:好的 :) 谢谢,我不知道。

标签: refactoring iterator python


【解决方案1】:

假设 Next 和 next 之一是拼写错误并且它们都是相同的,您可以使用内置 iter 函数的不太知名的变体:

for row in iter(cursor.next, None):
    <do something>

【讨论】:

  • 很好的答案!是的,功能是相同的(更糟糕的是,它们不区分大小写!)。
【解决方案2】:

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

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

【讨论】:

  • 我也喜欢这种方法。如果我需要包装的不仅仅是光标迭代,我可能会考虑以这种方式包装 gp
【解决方案3】:

最好的方法是在 table 对象周围使用 Python 迭代器接口,恕我直言:

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

在我看来,它非常易读。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-18
    • 2010-11-21
    • 1970-01-01
    • 2011-04-19
    • 2011-05-04
    • 2018-11-28
    • 2018-03-17
    • 2016-11-17
    相关资源
    最近更新 更多