問題描述
我可以在 Python 中重置迭代器/生成器嗎?我正在使用 DictReader 并希望將其重置為文件的開頭.
Can I reset an iterator / generator in Python? I am using DictReader and would like to reset it to the beginning of the file.
推薦答案
我看到很多答案建議 itertools.tee,但這忽略了文檔中的一個重要警告:
I see many answers suggesting itertools.tee, but that's ignoring one crucial warning in the docs for it:
此迭代工具可能需要大量輔助存儲(取決于如何需要大量臨時數據存儲).一般來說,如果一個迭代器使用之前的大部分或全部數據另一個迭代器啟動,它更快使用 list()
而不是 tee()
.
This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use
list()
instead oftee()
.
基本上,tee
是為這樣的情況設計的 - 相反,他們說的是同一個附近"(一些項目彼此落后或領先).不適合OP的從頭重做"的問題.
Basically, tee
is designed for those situation where two (or more) clones of one iterator, while "getting out of sync" with each other, don't do so by much -- rather, they say in the same "vicinity" (a few items behind or ahead of each other). Not suitable for the OP's problem of "redo from the start".
L = list(DictReader(...))
另一方面是非常合適的,只要字典列表可以舒適地放入內存中.可以隨時使用 iter(L)
制作一個新的從頭開始的迭代器"(非常輕量級和低開銷),并部分或全部使用而不影響新的或現有的;其他訪問模式也很容易獲得.
L = list(DictReader(...))
on the other hand is perfectly suitable, as long as the list of dicts can fit comfortably in memory. A new "iterator from the start" (very lightweight and low-overhead) can be made at any time with iter(L)
, and used in part or in whole without affecting new or existing ones; other access patterns are also easily available.
正如幾個答案正確指出的那樣,在 csv
的特定情況下,您還可以 .seek(0)
底層文件對象(一種相當特殊的情況).盡管目前確實有效,但我不確定是否已記錄并保證.僅對于真正巨大的 csv 文件可能值得考慮,其中我推薦的 list
因為一般方法會占用太大的內存.
As several answers rightly remarked, in the specific case of csv
you can also .seek(0)
the underlying file object (a rather special case). I'm not sure that's documented and guaranteed, though it does currently work; it would probably be worth considering only for truly huge csv files, in which the list
I recommmend as the general approach would have too large a memory footprint.
這篇關于可以在 Python 中重置迭代器嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!