我知道iterator
是iterable
,但只有1次通过。
例如itertools
中的很多函数都以iterable
为参数,例如islice
。如果我看到 api 显示 iterable
,我是否可以始终传入 iterator
?
正如@delnan 指出的那样:
Although every
iterator
is aniterable
, some people (outside the core team) say "iterable" when they mean "something that can be iterated several times with with the same results". Some code in the wild claims to work oniterables
but actually doesn't work withiterators
.
这正是我所关心的。那些支持多 channel 的 iterable
是否有名称?像 C# 中的 IEnumerable
吗?
如果我要构建一个声称支持 iterable
的函数,那么实际上是否也支持 iterator
是最佳实践?
最佳答案
是的,itertools 中的函数是为与迭代器一起使用而设计的。函数签名说 iterable
的原因是因为它们也适用于列表、元组和其他不是迭代器的可迭代对象。
A sequence是一个可迭代对象,它支持通过 __getitem__()
特殊方法使用整数索引进行高效元素访问,并定义了一个返回序列长度的 len()
方法。
这个定义与不是迭代器的所有可迭代对象的集合略有不同。 (您可以定义一个(残缺的)自定义类,它有一个 __getitem__
方法,但没有一个 __len__
。它将是一个不是迭代器的可迭代对象——但也不会它是一个序列
。)
但是 sequences
非常接近您正在寻找的内容,因为所有序列都是可迭代的,可以迭代多次。
sequence types 的例子内置于 Python 中的包括 str
、unicode
、list
、tuple
、bytearray
、buffer
和 xrange
。
以下是从 glossary 中剔除的一些定义:
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
关于python - 以可迭代作为参数的函数是否总是接受迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19643855/