用法:
itertools.tee(iterable, n=2)
從單個可迭代對象返回
n
獨立迭代器。以下 Python 代碼有助於解釋
tee
確實(雖然實際的實現更複雜並且隻使用一個底層FIFO隊列)。大致相當於:
def tee(iterable, n=2): it = iter(iterable) deques = [collections.deque() for i in range(n)] def gen(mydeque): while True: if not mydeque: # when the local deque is empty try: newval = next(it) # fetch a new value and except StopIteration: return for d in deques: # load it to all the deques d.append(newval) yield mydeque.popleft() return tuple(gen(d) for d in deques)
一旦
tee()
進行了拆分,原來的iterable
不應在其他任何地方使用;否則,iterable
可以在不通知 tee 對象的情況下前進。tee
迭代器不是線程安全的。 ARuntimeError
可能會在同時使用由同一tee()
調用返回的迭代器時引發,即使原始iterable
是線程安全的。此迭代工具可能需要大量輔助存儲(取決於需要存儲多少臨時數據)。通常,如果一個迭代器在另一個迭代器啟動之前使用了大部分或全部數據,則使用
list()
而不是tee()
會更快。
相關用法
- Python itertools.takewhile用法及代碼示例
- Python itertools.compress用法及代碼示例
- Python itertools.dropwhile用法及代碼示例
- Python itertools.repeat用法及代碼示例
- Python itertools.combinations_with_replacement用法及代碼示例
- Python itertools.groupby()用法及代碼示例
- Python itertools.repeat()用法及代碼示例
- Python itertools.count用法及代碼示例
- Python itertools.starmap用法及代碼示例
- Python itertools.filterfalse用法及代碼示例
- Python itertools.chain.from_iterable用法及代碼示例
- Python itertools.groupby用法及代碼示例
- Python itertools.zip_longest用法及代碼示例
- Python itertools.accumulate用法及代碼示例
- Python itertools.combinations用法及代碼示例
- Python itertools.permutations用法及代碼示例
- Python itertools.product用法及代碼示例
- Python itertools.chain用法及代碼示例
- Python itertools.cycle用法及代碼示例
- Python itertools.islice用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 itertools.tee。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。