使用迭代器

Python中的迭代器实现了一种迭代器模式,让我们能够一个接一个的处理一个序列,但不需要真正实现整个序列 在数据科学中,面对数据集特别大,内存不够的时候可以使用迭代器来逐个读取数据

定义了一个类SimpleCounter,在Python中想要成为一个迭代器的对象必须支持这两个函数,iter和next。iter函数用来返回整个类对象作为一个迭代器对象,next对象返回迭代器中的下一个值


In [1]:
# write a simple iterator
class SimpleCounter(object):
    def __init__(self,start,end):
        self.current = start
        self.end = end
    
    def __iter__(self):
        return self
    
    def next(self):
        if self.current > self.end:
            raise StopIteration
        else:
            self.current +=1
            return self.current - 1
        
# access the iterator
c = SimpleCounter(1,5)

In [7]:
print c.next()


---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-7-81c4998b88a1> in <module>()
----> 1 print c.next()

<ipython-input-1-e41dd6988a9c> in next(self)
     10     def next(self):
     11         if self.current > self.end:
---> 12             raise StopIteration
     13         else:
     14             self.current +=1

StopIteration: 

In [9]:
c = SimpleCounter(1,5)
for entry in iter(c):
    print entry


1
2
3
4
5

In [10]:
# generate iterator 
# 使用生成器创建迭代器

SimpleCounter = (x**2 for x in range(1,10))
total = 0
for val in SimpleCounter:
    total += val

print total


285

In [11]:
# 使用yield语句创建一个生成器 
def my_gen(low,high):
    for x in range(low,high):
        yield x**2

total = 0
for val in my_gen(3,7):
    total += val

print total


86

使用可迭代对象

可迭代对象和生成器很像,但是最主要区别是,可以重复的访问一个可迭代对象,生成器不是的。


In [12]:
# 先创建一个简单的带有iter方法的类
class SimpleIterable():
    
    def __init__(self,start,end):
        self.start = start
        self.end = end
        
    def __iter__(self):
        for x in range(self.start,self.end):
            yield x**2
            
# 现在调用这个类
c = SimpleIterable(1,10)

# 第一次迭代
total = 0
for val in iter(c):
    total += val
    
print total

# 第二次迭代
total = 0
for val in iter(c):
    total += val
    
print total


285
285