Python(2.7.6) 迭代器

除了对列表、集合和字典等进行迭代,还能对其他对象进行迭代:实现 __iter__ 方法的对象。例如, 文件对象就是可迭代的:

>>> dir(file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'closed', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

file 实现了 __iter__ 方法,我们便可以像迭代列表那样迭代文件对象:

f = open('f.txt')
for line in f:
    print line
f.close()

在 Python 2.x 中,一个实现了 __iter__ 方法的对象称之为可迭代的,一个实现了 next 方法的对象称之为迭代器。__iter__ 方法返回一个迭代器,迭代器在执行 next 方法时,会返回它的下一个值。如果 next 方法被调用,但迭代器没有值可以返回,则引发一个 StopIteration 异常。下面是一个返回斐波那契数列的迭代器。

class Fibonacci(object):
    def __init__(self, n):
        super(Fibonacci, self).__init__()
        self.n = n
        self.a = 0
        self.b = 1
    def next(self):
        self.a, self.b = self.b, self.a + self.b
        if self.a > self.n:
            raise StopIteration()
        return self.a
    def __iter__(self):
        return self

for f in Fibonacci(100):
    print f

Fibonacci 实现了 next 方法,所以它是一个迭代器, __iter__ 返回的迭代器本身。

 

内置函数 iter 可以从可迭代的对象中获得迭代器:

>>> it = iter([1, 2, 3])
>>> it.next()
1
>>> it.next()
2
>>> it.next()
3
>>> it.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

 

可以通过 list 构造方法显示地将迭代器转换为列表:

fibs = Fibonacci(100)
list(fibs)

一般情况下,推荐使用迭代器而不是列表,特别是当数据量非常大的时候。迭代器每次调用只返回一个值,而列表则一次性获得所有值,如果数据量很大,列表就会占用很多的内存。

posted on 2015-03-25 23:15  huey2672  阅读(1255)  评论(0编辑  收藏  举报