簡體   English   中英

迭代的更多pythonic方式

[英]More pythonic way to iterate

我正在使用屬於商業軟件API的模塊。 好消息是有一個python模塊 - 壞消息是它非常unpythonic。

要迭代行,使用以下語法:

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>

您可以創建一個自定義包裝器,如:

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)

另請參見: 迭代器類型

最好的方法是在table對象周圍使用Python迭代器接口,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

在我看來,它非常易讀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM