我使用的模块是商业软件 API 的一部分。好消息是有一个 python 模块——坏消息是它非常不符合 pythonic。
要遍历行,使用以下语法:
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
这是一个改进,但感觉有点笨拙。有没有更pythonic的方法?我应该围绕 table
类型创建一个包装器类吗?
最佳答案
假设 Next 和 next 中的一个是拼写错误并且它们是相同的,您可以使用内置 iter 函数的不太知名的变体:
for row in iter(cursor.next, None):
<do something>
关于refactoring - 更多pythonic迭代方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2980031/