classDepthFirstIterator(object):'''Depth-first traversal'''def__init__(self, start_node):
self._node = start_node
self._children_iter =None
self._child_iter =Nonedef__iter__(self):# 迭代器返回自身return self
def__next__(self):# Return myself if just started; create an iterator for childrenif self._children_iter isNone:
self._children_iter =iter(self._node)return self._node
# If processing a child, return its next itemelif self._child_iter:try:
nextchild =next(self._child_iter)return nextchild
except StopIteration:
self._child_iter =Nonereturnnext(self)# Advance to the next child and start its iterationelse:
self._child_iter =next(self._children_iter).depth_first()returnnext(self)
root = Node(0)
child1 = Node(1)
child2 = Node(2)
root.add_child(child1)
root.add_child(child2)for ch in root:print(ch)
反向迭代
# f = open('test.txt')# for line in reversed(list(f)): # 转换列表需要消耗大量内存# print(line, end='')# 实现 __reversed__()classCountdown:def__init__(self, start):
self.start = start
# Forward iteratordef__iter__(self):
n = self.start
while n >0:yield n
n -=1# Reverse iteratordef__reversed__(self):
n =1while n <= self.start:yield n
n +=1# for r in reversed(Countdown(30)):# print(r)
带有外部状态的生成器函数
# 暴露给用户使用的外部状态值classlinehistory:def__init__(self, lines, histlen=3):
self.lines = lines
self.history = deque(maxlen=histlen)def__iter__(self):for lineno, line inenumerate(self.lines,1):
self.history.append((lineno, line))yield line
defclear(self):
self.history.clear()# 打印含有python的histlen行文档withopen('test.txt')as f:
lines = linehistory(f)for line in lines:if'python'in line:for lineno, hline in lines.history:print('{}:{}'.format(lineno, hline), end='')
迭代器切片
# islice()返回一个可以生成指定元素的迭代器defaddone(n):whileTrue:yield n
n +=1
c = addone(0)for x in itertools.islice(c,10,20):# [begin,end)print(x)# 跳过可迭代对象的开始部分# dropwhile() 函数。使用时,你给它传递一个函数对象和一个可迭代对象。# 它会返回一个迭代器对象,丢弃原有序列中直到函数返回 Flase 之前的所有元素,然后返回后面所有元素。# with open('test.txt') as f:# for line in itertools.dropwhile(lambda line: line.startswith('#'), f):# print(line, end='')
顺序迭代合并
a =[1,4,7,10]
b =[2,5,6,11]# for x in heapq.merge(a, b):# print(x)# print(heapq.merge(a, b)) # 生成器print(list(heapq.merge(a, b)))