【发布时间】: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,所以在真实数据之后,这将永远循环,row是None。 -
@Felix King:差不多,但是因为迭代器通过引发 StopIteration 发出终止信号,
for row in cursor:将遍历行,然后给出Nones 的无限流。 -
@Matthew, @Paul:好的 :) 谢谢,我不知道。
标签: refactoring iterator python