在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()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。