refactoring - 更多pythonic迭代方式

标签 refactoring iterator python

我使用的模块是商业软件 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/

相关文章:

javascript - 在 Facebook React 中使用混合与组件进行代码重用

c# - 这真的是一个改进吗(当内部范围处于循环中时将 var 移动到内部范围)?

java - 为什么我们不能为 Iterator<IFoo> 返回 ArrayList<Foo>.iterator() ?

Python-pptx:复制幻灯片

python - 类型错误 : _get_loc_req() takes at least 3 arguments (1 given) - Odoo v8 to Odoo v10 community

vim - 你的 .vimrc 中有什么?

java - 使用迭代器进行 "downward"次迭代的优雅方式

java - Iterable 和 Iterator 接口(interface)的使用

python - 在 PyCharm 中查找调用 Python 函数的位置

c# - 在列表中查找匹配项的最简洁方法