python生成器使用场景_Python 中迭代器与生成器实例详解

Python 中迭代器与生成器实例详解

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

1.手动遍历迭代器

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

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

?

1

2

3

4

5

6

7

8

9

10

def manual_iter():

withopen('/etc/passwd') as f:

try:

while True:

line=next(f)

if lineis None:

break

print(line,end='')

except StopIteration:

pass

?

1

2

3

4

5

6

#test case

items=[1,2,3]

it=iter(items)

next(it)

next(it)

next(it)

2.代理迭代

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

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

示例:

?

1

2

3

4

5

6

7

8

9

10

11

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)

?

1

2

3

4

5

6

7

8

9

#test case

if __name='__main__':

root=Node(0)

child1=Node(1)

child2=Nide(2)

root.add_child(child1)

root.add_child(child2)

for chin root:

print(ch)

3.反向迭代

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

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

示例1

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

a=[1,2,3,4]

for xin reversed(a):

print(x)#4 3 2 1

f=open('somefile')

for linein reversed(list(f)):

print(line,end='')

#test case

for rrin reversed(Countdown(30)):

print(rr)

for rrin Countdown(30):

print(rr)

示例2

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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

?

1

2

3

withopen('/etc/passwd') as f:

for linein f:

print(line,end='')

示例2

?

1

2

3

4

from itertoolsimport dropwhile

withopen('/etc/passwd') as f:

for linein dropwhile(lambda line:line.startwith('#'),f):

print(line,end='')

5.同时迭代多个序列

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

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

1051215332-0.png

1051211348-1.png

1051211240-2.png

1051212C1-3.png

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

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

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

1051211011-4.png

7.展开嵌套的序列

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

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

示例

?

1

2

3

4

5

6

7

from collectionsimport Iterable

def flatten(items,ignore_types=(str,bytes)):

for xin items:

if isinstance(x,Iterable)and not isinstance(x,ignore_types):

yield from flatten(x)

else:

yield x

?

1

2

3

4

#test case

items=[1,2,[3,4,[5,6],7],8]

for xin flatten(items):

print(x)

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/arthur_02_13/article/details/67634292

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值