Python – Itertools.tee()
在Python中,Itertools 是内置模块,它允许我们以有效的方式处理迭代器。它们使迭代列表和字符串等可迭代对象变得非常容易。一个这样的 itertools函数是filterfalse()。
注意:更多信息请参考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']