您的位置:首页 > 编程语言 > Python开发

Python学习总结-迭代器与生成器

2017-03-28 12:29 656 查看
本文通过针对不同应用场景及其解决方案的方式,总结了Python中迭代器与生成器的一些相关知识,具体如下:

1.手动遍历迭代器

应用场景:想遍历一个可迭代对象中的所有元素,但是不想用for循环

解决方案:使用next()函数,并捕获StopIteration异常

def manual_iter():
with open('/etc/passwd') as f:
try:
while True:
line=next(f)
if line is None:
break
print(line,end='')
except StopIteration:
pass


#test case
items=[1,2,3]
it=iter(items)
next(it)
next(it)
next(it)


2.代理迭代

应用场景:想直接在一个包含有列表、元组或其他可迭代对象的容器对象上执行迭代操作

解决方案:定义一个iter()方法,将迭代操作代理到容器内部的对象上

示例:
class Node:
def __init__(self,value):
self._value=value
self._children=[]
def __repr__(self):
return 'Node({!r})'.fromat(self._value)
def add_child(self,node):
self._children.append(node)
def __iter__(self):
#将迭代请求传递给内部的_children属性
return iter(self._children)


#test case
if __name='__main__':
root=Node(0)
child1=Node(1)
child2=Nide(2)
root.add_child(child1)
root.add_child(child2)
for ch in root:
print(ch)


3.反向迭代

应用场景:想要反向迭代一个序列

解决方案:使用内置的reversed()函数或者在自定义类上实现reversed()

示例1
a=[1,2,3,4]
for x in reversed(a):
print(x) #4 3 2 1

f=open('somefile')
for line in reversed(list(f)):
print(line,end='')
#test case
for rr in reversed(Countdown(30)):
print(rr)

for rr in Countdown(30):
print(rr)


示例2
class Countdown:
def __init__(self,start):
self.start=start
#常规迭代
def __iter__(self):
n=self.start
while n > 0:
yield n
n -= 1
#反向迭代
def __reversed__(self):
n=1
while n <= self.start:
yield n
n +=1


4.有选择的迭代

应用场景:想遍历一个可迭代对象,但是对它开始的某些元素并不感兴趣,想跳过

解决方案:使用itertools.dropwhile()

示例1
with open('/etc/passwd') as f:
for line in f:
print(line,end='')


示例2
from itertools import dropwhile
with open('/etc/passwd') as f:
for line in dropwhile(lambda line:line.startwith('#'),f):
print(line,end='')


5.同时迭代多个序列

应用场景:想同时迭代多个序列每次分别从一个序列中取一个元素

解决方案:使用zip()函数









6.不同集合上元素的迭代

应用场景:想在多个对象执行相同的操作,但是这些对象在不同的容器中

解决方案:使用itertool.chain()函数



7.展开嵌套的序列

应用场景:想将一个多层嵌套的序列展开成一个单层列表

解决方案:使用包含yield from语句的递归生成器

示例
from collections import Iterable
def flatten(items,ignore_types=(str,bytes)):
for x in items:
if isinstance(x,Iterable) and not isinstance(x,ignore_types):
yield from flatten(x)
else:
yield x


#test case
items=[1,2,[3,4,[5,6],7],8]
for x in flatten(items):
print(x)


8.实现迭代器协议

应用场景:你想构建一个能支持迭代操作的自定义对象,并希望找到一个能实现迭代协议的简单方法。

解决方案:使用NodeTree类来表示树形数据结构,想实现一个以深度优先方式遍历树形节点的生成器。

#使用一个关联迭代器实现depth_first()
class NodeTree:
def __init__(self,value):
self._value=value
self._children=[]
def __repr__(self):
return 'Node({!r})'.format(self._value)
def add_child(self,node):
self._children.append(node)
def __iter__(self):
return iter(self._children)
def depth_first(self):
return DepthFirstIterator(self)

class DepthFirstIterator(object):
def __init__(self,start_node):
self._node=start_node
self._children_iter=None
self._child_iter=None
def __iter__(self):
return self
def __next__(self):
#没有子节点则返回自身;并给子节点创建一个迭代器
if self._children_iter is None:
self._children_iter=iter(self._node)
return self._node
#处理子节点,返回其下一层
elif self._child_iter:
try:
nextchild=next(self._child_iter)
return nextchild
except:
self._child_iter=None
return next(self)
#调到下一个子节点并开始迭代
else:
self._child_iter=next(self._children_iter).depth_first()
return next(self)


#用生成器代替上面的DepthFirstIterator
class NodeTree1:
def __init__(self,value):
self._value=value
self._children=[]
def __repr__(self):
return 'Node({!r})'.format(self._value)
def add_child(self,node):
self._children.append(node)
def __iter__(self):
return iter(self._children)
def depth_first(self):
yield self
for c in self:
yield from c.depth_first()

#test case
if __name__=='__main__':
root=NodeTree1(0)
child1=NodeTree1(1)
child2=NodeTree1(2)
root.add_child(child1)
root.add_child(child2)
child1.add_child(NodeTree1(3))
child2.add_child(NodeTree1(4))
child2.add_child(NodeTree1(5))
for ch in root.depth_first():
print(ch)#Node(0)...Node(5)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 迭代器 生成器