1

標準的なアウェイは次のとおりです。

it = iter(sequence)
for value in it:
    print value

最初の値がヘッダー、2 番目の値がメタデータ、残りの値がレコードの反復子を返すサード パーティのライブラリを使用しています。私は次のようなことを試しました:

db = dbfreader(f)
headers = db.next()
spec =  db.next()
record = db.next()
while record:
    print record
    record = db.next()

しかし、それは StopIteration エラーになります

4

2 に答える 2

5

The first record is not special, it's just the first of all records, so there's no reason to read it ahead of time.

db = dbfreader(f)
headers = db.next()
spec =  db.next()
for record in db:
    print record
于 2013-04-06T01:51:39.520 に答える
1

The standard way is:

it = iter(sequence)
for value in it:
    print value

No need for the call to iter here, it gets done implicitly in the loop:

for value in sequence:
    print value

Ultimately, iter(obj) returns obj.__iter__(). This gets called implicitly when you start a for loop:

for elem in x:

implicitly does

for elem in iter(x):

Then, in the loop, python calls next on the iterable returned by iter(obj) to get the various elems until next raises a Stopiteration.

So your loop could be written as:

while True:
    print record
    try:
        record = next(db)
    except StopIteration:
        break

Or more succinctly and idiomatically (as long as iter(db) returns db which is pretty typical):

for record in db:
    print record

Generally, you can get the next value from an iterable using the next function -- but the object needs to have a next method (or __next__ on python3.x). If it's a sequence, you might need to call iter on the object first in this case:

>>> obj = ['header','header2','record1']
>>> next(obj)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list object is not an iterator
>>> iobj = iter(obj)
>>> next(iobj)
'header'
>>> next(iobj)
'header2'
>>> for x in iobj:
...    print x
... 
record1

Note that you can suppress a StopIteration from being raised by next by supplying a second argument to be returned instead of raising StopIteration:

>>> next(iter([]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> next(iter([]),"Hello!")
'Hello!'

Seeing this, we find that you could also write your loop:

while record:
    print record
    record = next(db,False)

But the for loop is definitely the cleanest way to do it for most objects.

于 2013-04-06T01:50:15.393 に答える