Iterators(关键词:Python/iterator/iterable/__iter__/next)

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
        break1597
    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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值