簡體   English   中英

使用python'with'語句與迭代器?

[英]using python 'with' statement with iterators?

我正在使用Python 2.5。 我正在嘗試使用這個'with'語句。

from __future__ import with_statement
a = []
with open('exampletxt.txt','r') as f:
    while True:
        a.append(f.next().strip().split())
print a

'exampletxt.txt'的內容很簡單:

a
b

在這種情況下,我收到錯誤:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/tmp/python-7036sVf.py", line 5, in <module>
    a.append(f.next().strip().split())
StopIteration

如果我用f.next()替換f.read() ,它似乎陷入無限循環。

我想知道是否必須編寫一個接受迭代器對象作為參數的裝飾器類,並為它定義一個__exit__方法?

我知道使用for循環迭代器更加pythonic,但我想在一個由for循環調用的生成器中實現一個while循環... 類似於

def g(f):
    while True:
        x = f.next()
        if test1(x):
            a = x
        elif test2(x):
            b = f.next()
            yield [a,x,b]

a = []
with open(filename) as f:
    for x in g(f):
        a.append(x)

提升StopIteration是迭代器到達時的作用。 通常, for語句會以靜默方式捕獲它並繼續執行else子句,但如果它是在您的情況下手動迭代那么代碼必須准備好處理異常本身。

你的while循環沒有結束,但文件是這樣做的,當沒有其他東西可以迭代時,它會引發一個StopIteration異常。

在任何while循環中都沒有任何終止條件,所以你一直返回,直到你得到你不能處理的StopIteration異常。

您可以隨時重寫with-with-explicit-next循環。 當你有明確的next ,你只是向前看一個令牌。

通常,可以重寫此形式的循環。

def g(f):
    while True:
        x = f.next()
        if test1(x):
            a = x
        elif test2(x):
            b = f.next()
            yield [a,x,b]

您可以隨時更換前瞻next通過緩沖值。

def g(f):
    prev, a = None, None
    for x in f:
        if test2(prev)
            yield [ a, prev, x ]
        elif test1(x):
            a = x
        prev= x

暫無
暫無

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

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