Iterator Or Generator -- That Is The Question?
时间:2007-07-25 来源:wxPhoenix
class Reverser:
"""Iterator for looping over a seqence backwards"""
def __init__(self, seq)
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index -= 1
return self.data[self.index]
def reverse(data):
"""Generator for looping over a sequence badkwards"""
for index in range(len(data)-1, -1, -1):
yield data[index]
# Iterator和Generator都可以用于迭代,如何在它们之间做出选择?
# 只有一点:Iterator展现的是Sequence的功能,这是一种结果!
# Generator则不然,它体现的是一种过程性行为, 即产即"消",
# 遵循"零库存"原则!
相关阅读 更多 +