python - 以可迭代作为参数的函数是否总是接受迭代器?

标签 python iterator

我知道iteratoriterable,但只有1次通过。

例如itertools中的很多函数都以​​iterable为参数,例如islice。如果我看到 api 显示 iterable,我是否可以始终传入 iterator

正如@delnan 指出的那样:

Although every iterator is an iterable, 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 on iterables but actually doesn't work with iterators.

这正是我所关心的。那些支持多 channel 的 iterable 是否有名称?像 C# 中的 IEnumerable 吗?

如果我要构建一个声称支持 iterable 的函数,那么实际上是否也支持 iterator 是最佳实践?

最佳答案

是的,itertools 中的函数是为与迭代器一起使用而设计的。函数签名说 iterable 的原因是因为它们也适用于列表、元组和其他不是迭代器的可迭代对象。


A sequence是一个可迭代对象,它支持通过 __getitem__() 特殊方法使用整数索引进行高效元素访问,并定义了一个返回序列长度的 len() 方法。

这个定义与不是迭代器的所有可迭代对象的集合略有不同。 (您可以定义一个(残缺的)自定义类,它有一个 __getitem__ 方法,但没有一个 __len__。它将是一个不是迭代器的可迭代对象——但也不会它是一个序列。)

但是 sequences 非常接近您正在寻找的内容,因为所有序列都是可迭代的,可以迭代多次。

sequence types 的例子内置于 Python 中的包括 strunicodelisttuplebytearraybufferxrange


以下是从 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/

相关文章:

Python 3.6 没有名为 pip 的模块

c++ - 将指针包装到迭代器中以复制到 STL 容器中

java - 为什么迭代器没有任何重置方法?

rust - 如何使用特征实现迭代器

javascript - Python 在警报中单击按钮

python - 正常随边界变化?

python - 如何获取特定文件的图标或缩略图

python - 使用 multiprocessing.dummy 并行请求

c++ - 将 map<>::iterator 作为 map<>::const_iterator &

c++ - zip_iterator 和 lower_bound