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

2024-10-01 09:28:29 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例如,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.

这正是我所关心的。支持多路径的iterable有名字吗?像C中的IEnumerable?在

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


Tags: the函数anapi参数iswithiterable
3条回答

您应该看看在the ^{} module中定义的抽象基类。就您的目的而言,Container或{}可能是最有用的,因为它们分别需要__contains__和{},而这又需要一组定义良好的值,这些值可以重复迭代。在

是的,因为每个迭代器也是iterable。在

如果一个对象定义了__iter__()方法,那么它就是iterable。每个迭代器都有这个方法,它返回迭代器本身。在

是的,itertools中的函数是为迭代器设计的。函数签名之所以说iterable,是因为它们还处理列表、元组和其他不是迭代器的iterable。在


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

这个定义与不是迭代器的所有iterable的集合稍有不同。(您可以定义一个(残废的)自定义类,它有一个__getitem__,但没有__len__。它将是一个iterable,它不是迭代器,但也不是sequence。)

但是sequences非常接近您要查找的内容,因为所有序列都是可重复多次的iterable。在

内置到Python中的sequence types示例包括strunicodelisttuplebytearraybuffer和{}。在


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

相关问题 更多 >