您的位置:首页 > 编程语言 > Python开发

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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息