我知道iterator
是iterable
,但是只有1次通过。
例如,许多函数都itertools
采用iterable
作为参数,例如islice
。iterator
如果我看到api说的话,可以一直通过iterable
吗?
正如@delnan指出的那样:
尽管每个人
iterator
都是一个人iterable
,但某些人(核心团队之外)说“可迭代”时表示“可以迭代多次且结果相同”。一些狂野的代码声称可以使用,iterables
但实际上不起作用iterators
。
这正是我的关注。iterable
支持多通的人有名字吗?像IEnumerable
在C#中一样?
如果我要构建一个声称要支持的功能iterable
,那么实际上也是最好的做法iterator
吗?
是的,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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句