Iterators(关键词:Python/iterator/iterable/__iter__/next)
2017-09-10 21:01
861 查看
Iterators
I’ve mentioned iterators (and iterables) briefly in preceding chapters. In this section, I go into some more detail. I cover only one magic method, iter, which is the basis of the iterator protocol.
The Iterator Protocol
To iterate means to repeat something several times—what you do with loops. Until now I have iterated over only sequences and dictionaries in for loops, but the truth is that you can iterate over other objects, too: objects that implement the iter method. The iter method returns an iterator, which is any object with a method called next, which is callable without any arguments. When you call the next method, the iterator should return its “next value.” If the method is called, and the iterator has no more values to return, it should raise a StopIteration exception.
■Note The iterator protocol is changed a bit in Python 3.0. In the new protocol, iterator objects should have a method called next rather than next, and a new built-in function called next may be used to access this method. In other words, next(it) is the equivalent of the pre-3.0 it.next().
What’s the point? Why not just use a list? Because it may often be overkill. If you have a function that can compute values one by one, you may need them only one by one—not all at once, in a list, for example. If the number of values is large, the list may take up too much memory. But there are other reasons: using iterators is more general, simpler, and more elegant. Let’s take a look at an example you couldn’t do with a list, simply because the list would need to be of infinite length! Our “list” is the sequence of Fibonacci numbers. An iterator for these could be the following:
class Fibs: def init(self): self.a = 0 self.b = 1 def next(self): self.a, self.b = self.b, self.a+self.b return self.a def iter(self): return self
Note that the iterator implements the iter method, which will, in fact, return the iterator itself. In many cases, you would put the iter method in another object, which you would use in the for loop. That would then return your iterator. It is recommended that iterators implement an iter method of their own in addition (returning self, just as I did here), so they themselves can be used directly in for loops.
■Note In formal terms, an object that implements the iter method is iterable, and the object implementing next is the iterator.
First, make a Fibs object:
fibs = Fibs()
You can then use it in a for loop—for example, to find the smallest Fibonacci number that is greater than 1,000:
>>> for f in fibs: if f > 1000: print f break … 1597
Here, the loop stops because I issue a break inside it; if I didn’t, the for loop would never end.
■Tip The built-in function iter can be used to get an iterator from an iterable object:
>>> it = iter([1, 2, 3]) >>> it.next() 1 >>> it.next() 2
It can also be used to create an iterable from a function or other callable object (see the Python Library Reference, http://docs.python.org/lib/, for details).
Making Sequences from Iterators
In addition to iterating over the iterators and iterables (which is what you normally do), you can convert them to sequences. In most contexts in which you can use a sequence (except in operations such as indexing or slicing), you can use an iterator (or an iterable object) instead. One useful example of this is explicitly converting an iterator to a list using the list constructor:
class TestIterator: value = 0 def next(self): self.value += 1 if self.value > 10: raise StopIteration return self.value def iter(self): return self … >>> ti = TestIterator() >>> list(ti) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
参考文献:
1.《Beginning Python》2nd Edition 第8章 Iterators。
相关文章推荐
- 迭代器(关键词:Python/iterator/iterable/__iter__/next)
- TypeError: iter() returned non-iterator of type 'xx' 从Python3开始,要用__next__
- Python中的itertools.combinations(iterable, r)(关键词:itertools/combinations)
- Python学习笔记(5) -- 迭代器(Iterable/Iterator/iter())
- Python iterable, iter(), __iter__, iterator, itertools
- python 3-1 如何实现可迭代对象iterable和迭代器对象iterator,__iter__,__getitem__
- 小白汪:Python学习之generator、Iterator关系及generator的send和next运行流程
- python Class: 面向对象高级编程 __iter__ 和 next()
- Python中的iterator——yield和__iter__
- iterator, __iter__, __next__
- Python 中 Iterator(迭代器)和Iterable(可迭代)的区别:
- Python 中 Iterator和Iterable的区别
- python之__iter__函数与__next__函数
- python基础----__next__和__iter__实现迭代器协议
- Python关键字yield详解以及Iterable 和Iterator区别
- python学习笔记之Iterable和Iterator的区别
- 零基础学python-13.2 手动迭代:iter和next
- python iterable与iterator,generator,generator expression
- Python高级特性(1):Iterators、Generators和itertools(转)
- 零基础学python-13.2 手动迭代:iter和next