簡體   English   中英

Python,如何一次又一次讀取同一文件時將枚舉的迭代器設置為0

[英]Python, how can I set iterator of enumerate to 0 while reading same file again and again

with open("...txt") as fp: 
    for i, line in enumerate(fp): 
        if some condition : 
            i=0
            fp.seek(0)

文本很大,數據的GB數很大,所以我使用枚舉。 我需要處理這個巨大的文件數千次,所以為了提高效率,我決定第一次打開它。 但是,盡管此代碼有效,但i並沒有變為0,而是繼續遞增。 我需要將其設為零,因為我需要第i行的位置。 每次乘以數十億*幾千並進行一些模運算只是效率低下。

所以我的問題是,當我回到文件開頭時,如何將i設置為零? 在此先感謝(我使用python 3.6)

你總是可以使自己的復位枚舉,但有可能是更好的方法做你真正想做的事情。

盡管如此,這還是一個可重置的枚舉器的樣子:

 def reset_enumerate(thing, start=0):
     x = start
     for t in thing:
         val = yield t, x
         if val is not None:
             x = val
         else:
             x += 1

然后,您將像這樣使用它:

r = reset_enumerate(range(10))
for i, num in r:
    print('i:', i, 'num:', num)     
    if i == 5:
        i, num = r.send(0)
        print('i:', i, 'num:', num)

這是一個如何模擬類似場景的示例:

假設我有一個名為input.txt的文件,其中包含這種數據:

1
2
3

碼:

j = 0
with open('input.txt', 'r') as f:
    for k in f:
        # A break condition
        # If not we'll face an infinite loop
        if j > 4:
            break
        if k.strip() == '2':
            f.seek(0)
            print("Return to position 0")
            # Don't forget to increment j 
            # Otherwise, we'll end up with an infinite loop
            j += 1
        print(k.strip())

將輸出:

1
Return to position 0
2
1
Return to position 0
2
1
Return to position 0
2
1
Return to position 0
2
1
Return to position 0
2

如評論中所述, enumerate是一個生成器函數。 完成時已經“精疲力盡”。 這也是為什么您不能僅僅“重置”它的原因。 這是列舉的PEP ,以進一步解釋其工作原理。

此外,正如評論中指出的那樣, 這篇文章提供了處理大型文件的典型方法。

暫無
暫無

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

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