Itertools is a Python module of functions that return generators, which are objects that only function when iterated over.
Itertools是返回生成器的函数的Python模块,生成器是仅在迭代时起作用的对象。
链() (chain())
The chain()
function takes several iterators as arguments. It goes through each element of each passed iterable, then returns a single iterator with the contents of all passed iterators.
chain()
函数采用多个迭代器作为参数。 它遍历每个传递的迭代器的每个元素,然后返回具有所有传递的迭代器内容的单个迭代器。
import itertools
list(itertools.chain([1, 2], [3, 4]))
# Output
# [1, 2, 3, 4]
islice() (islice())
The islice()
function returns specific elements from the passed iterator.
islice()
函数从传递的迭代器返回特定元素。
It takes the same arguments as the slice()
operator for lists: start, stop, and step. Start and stop are optional.
对于列表,它采用与slice()
运算符相同的参数:开始,停止和步进。 开始和停止是可选的。
import itertools
list(itertools.islice(count(), 5))
# Output
# [0, 1, 2, 3, 4]
izip() (izip())
izip()
returns an iterator that combines the elements of the passed iterators into tuples.
izip()
返回一个迭代器,该迭代器将传递的迭代器的元素合并为元组。
It works similarly to zip()
, but returns an iterator instead of a list.
它的工作方式类似于zip()
,但是返回一个迭代器而不是列表。
import itertools
list(izip([1, 2, 3], ['a', 'b', 'c']))
# Output
# [(1, 'a'),(2, 'b'),(3, 'c')]
更多信息: (More Information:)
Multithreaded Python: slithering through an I/O bottleneck 🍾
翻译自: https://www.freecodecamp.org/news/python-itertools-chain-isslice-and-izip-explained-with-examples/