是的,itertools 中的函数是为与迭代器一起使用而设计的。函数签名之所以这么说iterable
,是因为它们也适用于列表、元组和其他不是迭代器的可迭代对象。
序列是一个可迭代的,它通过__getitem__()
特殊方法支持使用整数索引进行有效的元素访问,并定义了一个len()
返回序列长度的方法。
这个定义与不是迭代器的所有可迭代对象的集合略有不同。(你可以定义一个(残缺的)自定义类,它有一个__getitem__
, 方法但没有一个__len__
。它将是一个不是迭代器的可迭代对象——但它也不是一个sequence
.)
但是sequences
非常接近您正在寻找的内容,因为所有序列都是可以迭代多次的可迭代对象。
Python 中内置的序列类型示例包括str
、unicode
、list
、tuple
、bytearray
和.buffer
xrange
以下是从词汇表中挑选出来的一些定义:
container
Has a __contains__ method
generator
A function which returns an iterator.
iterable
An object with an __iter__() or __getitem__() method. Examples of
iterables include all sequence types (such as list, str, and
tuple) and some non-sequence types like dict and file. When an
iterable object is passed as an argument to the builtin function
iter(), it returns an iterator for the object. This iterator is
good for one pass over the set of values.
iterator
An iterable which has a next() method. Iterators are required to
have an __iter__() method that returns the iterator object
itself. An iterator is good for one pass over the set of values.
sequence
An iterable which supports efficient element access using integer
indices via the __getitem__() special method and defines a len()
method that returns the length of the sequence. Note that dict
also supports __getitem__() and __len__(), but is considered a
mapping rather than a sequence because the lookups use arbitrary
immutable keys rather than integers. sequences are orderable
iterables.
deque is a sequence, but collections.Sequence does not recognize
deque as a sequence.
>>> isinstance(collections.deque(), collections.Sequence)
False