1

私が実行しているコードは次のとおりです。

with open('test.txt','r') as fin:
    for i,line in enumerate(fin):
        print i
        print fin.next()

「test.txt」は次のとおりです。

    5
    9 6
    4 6 8
    0 7 1 5 

私が得ている出力は次のとおりです。

0 
9 6 

1
0 7 1 5

「4 6 8」の行がスキップされている理由がわかりません。行 2 は最初の繰り返しで印刷され、行 3 は 2 回目の繰り返しで印刷され、行 4 は 3 回目の繰り返しで印刷されると予想していました。

代わりに、2 回目の反復で 4 行目を取得しています。

4

2 に答える 2

4

This is because when you do for i,line in enumerate(fin), the call to enumerate is already calling fin.next() under the hood. Therefore, when you call fin.next manually later on, you get the next line after the line that you are already processing. This is why you appear to skip lines.

If you want to observe more of this behavior, take a look at the output produced by the following snippet:

L1 = [1,2,3,4]
L2 = ['a', 'b', 'c', 'd']
print zip(L1, L2)

The output is:

[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd')] 

Compare that with the following snippet:

with open('test.txt','r') as fin:
    print zip(fin, fin)

Where the output is:

[('1 2 3 4\n' , 'a b c d \n')]

Do you now see why your output seemed to be skipping lines?

于 2013-08-26T21:34:10.313 に答える
3

fin.next()ファイルオブジェクトを繰り返し、finカーソルを次の行に移動しているため、while ループの先頭に戻ると、その行を「スキップ」したことになります。lineではなく、印刷したいfin.next()

于 2013-08-26T21:34:39.280 に答える