将iterable作为参数的函数是否总是接受迭代器?

col*_*ang 5 python iterator

我知道的iteratoriterable,但只有一次通过.

例如,许多功能中itertoolsiterable为参数,例如islice.iterator如果我看到api说的话,我可以随时通过iterable吗?

正如@delnan指出:

虽然每个iterator都是一个iterable,但有些人(在核心团队之外)说"可迭代",当他们的意思是"可以用相同的结果迭代几次".野外的一些代码声称可以使用iterables但实际上不起作用 iterators.

这是我的担忧.是否有iterable支持多通道的名称?喜欢IEnumerableC#?

如果我要构建一个声称支持的功能iterable,那么实际支持iterator也是最佳实践吗?

unu*_*tbu 5

是的,itertools中的函数设计用于迭代器.函数签名之所以说iterable是因为它们也适用于列表,元组和其他不是迭代器的迭代.


序列是一个可迭代的,它通过__getitem__()特殊方法使用整数索引支持有效的元素访问,并定义一个len()返回序列长度的方法.

此定义与不是迭代器的所有迭代集的集合略有不同.(你可以定义一个(残缺的)自定义类,它有一个__getitem__方法但不是一个__len__.它将是一个迭代,它不是迭代器 - 但它也不是sequence.)

然而,sequences它非常接近您所寻找的,因为所有序列都是可迭代的,可以多次迭代.

实例序列类型内建在Python中包括str,unicode,list,tuple,bytearray,bufferxrange.


以下是从词汇表中挑选出来的一些定义:

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
Run Code Online (Sandbox Code Playgroud)