在Python中,Itertools是內置模塊,可讓我們以高效的方式處理迭代器。它們非常容易地遍曆列表和字符串之類的可迭代對象。 filterfalse()是這樣的itertools函數之一。
注意:有關更多信息,請參閱Python Itertools。
tee()函數
該迭代器將容器拆分為參數中提到的多個迭代器。
用法:
tee(iterator, count)
參數:此方法包含兩個參數,第一個參數是迭代器,第二個參數是整數。
返回值:此方法返回參數中提到的迭代器的數量。
範例1:
# Python code to demonstrate the working of tee()  
    
# importing "itertools" for iterator operations  
import itertools  
    
# initializing list   
li = [2, 4, 6, 7, 8, 10, 20]  
    
# storing list in iterator  
iti = iter(li)  
    
# using tee() to make a list of iterators  
# makes list of 3 iterators having same values.  
it = itertools.tee(iti, 3)  
    
# printing the values of iterators  
print ("The iterators are:")  
for i in range (0, 3):  
    print (list(it[i])) 輸出:
The iterators are: [2, 4, 6, 7, 8, 10, 20] [2, 4, 6, 7, 8, 10, 20] [2, 4, 6, 7, 8, 10, 20]
範例2:
# Python code to demonstrate the working of tee()  
    
# importing "itertools" for iterator operations  
import itertools 
    
    
# using tee() to make a list of iterators  
  
iterator1, iterator2 = itertools.tee([1, 2, 3, 4, 5, 6, 7], 2) 
    
# printing the values of iterators  
print (list(iterator1))  
print (list(iterator1))  
print (list(iterator2)) 輸出:
[1, 2, 3, 4, 5, 6, 7] [] [1, 2, 3, 4, 5, 6, 7]
範例3:
# Python code to demonstrate the working of tee()  
    
# importing "itertools" for iterator operations  
import itertools 
    
    
# using tee() to make a list of iterators  
  
for i in itertools.tee(['a', 'b', 'c', 'd', 'e', 'f', 'g'], 4):
    # printing the values of iterators  
    print (list(i))輸出:
['a', 'b', 'c', 'd', 'e', 'f', 'g'] ['a', 'b', 'c', 'd', 'e', 'f', 'g'] ['a', 'b', 'c', 'd', 'e', 'f', 'g'] ['a', 'b', 'c', 'd', 'e', 'f', 'g']
相關用法
注:本文由純淨天空篩選整理自SHUBHAMSINGH10大神的英文原創作品 Python – Itertools.tee()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
