Python系统学习第二十七课

迭代器

  • 可迭代(iterable):直接作用于for循环的变量
  • 迭代器(iterator):不但可以直接作用于for循环,还可以被next调用
  • list是典型的可迭代对象,不是迭代器
  • 通过isinstance判断
  • iterable和iterator可以转换
    • 通过iter函数可以转换
#可迭代
l = [i for i in range(1,10)]
for i in l:
    print(i)
    
#range是一个迭代器
for i in range(5):
    print(i)
1
2
3
4
5
6
7
8
9
0
1
2
3
4
# isinstance案例
#判断某一个变量是否是一个实例
#判断是否可以迭代
from collections import Iterable
l1 = [1,2,3,4,5]

print(isinstance(l1, Iterable))

from collections import Iterator

print(isinstance(l1, Iterator))
True
False

生成器

  • generator:一边循环一边计算下一个元素的机制/算法
  • 需要满足三个条件:
    • 每次调用都产生出for循环需要的写一个元素或者
    • 如果达到最后一个后,一定会爆出stopIteration异常,否则说明就有问题
    • 可以被next函数调用
  • 如何生成一个生成器
    • 直接使用
    • 自己写一个生成器,函数中包含yield,则这个函数就叫生成器
    • next调用函数,遇到yield返回
# 直接使用生成器
l = [x*x for x in range(5)]   #放在中括号里边是列表生成器
g = (x*x for x in range(5))   #放在小括号里边就是生成器

print(type(l))
print(type(g))
<class 'list'>
<class 'generator'>
#函数案例
def odd():
    print("aa")
    yield 1
    print("bb")
    yield 2
    print("cc")
    yield 3
    return None
#odd()是调用生成器
f = odd()
o = next(f)
print(o)
s = next(f)
print(s)
t = next(f)
print(t)
aa
1
bb
2
cc
3
#for循环调用生成器
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        a,b = b, a+b
        n+=1
    return "Done"
fib(5)
1
1
2
3
5





'Done'
#斐波那契数列的sheng
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a,b = b, a+b
        n+=1
    return "Done"
q = fib(5)
for i in range(6):
    w = next(q)
    print(w)
1
1
2
3
5



---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

<ipython-input-25-fc7a341a05c9> in <module>()
      9 q = fib(5)
     10 for i in range(6):
---> 11     w = next(q)
     12     print(w)


StopIteration: Done

协程

  • 协程是为了非抢占式多任务产生子程序的计算机程序组件,协程允许不同入口点在不同位置暂停或开始执行程序
  • 从技术的角度讲,就是一个你可以暂停执行的函数,或者干脆把协程理解成生成器
  • 协程的实现
    • yield返回
    • send调用
  • 协程的四个状态

  • 协程终止
    • 协程中未处理的异常会向上冒泡,传给next函数或者send方法的调用方(即触发协程的对象)
    • 止协程的一种方式:发送某个哨符值,让协程退出,内置的None和Ellipisis等常量经常用作哨符值==
  • yield from
    • 调用协程为了得到返回值,协程必须正常终止
    • 生成器正常终止会发出StopIteration异常,异常对象的value属性保存返回值
    • yield from 从内部捕获StopIteration异常
def simple_coroutine():
    print('-> start')
    x = yield
    print('-> recived', x)
#主线程
sc = simple_coroutine()
print(1111)
# 可以使用sc.send(None),效果一样
next(sc)   #预激

print(2222)
sc.send('zhexiao')    #send参数赋值给x
1111
-> start
2222
-> recived zhexiao



---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

<ipython-input-26-a47ab19588a7> in <module>()
     10 
     11 print(2222)
---> 12 sc.send('zhexiao')


StopIteration: 
#协程的状态
def simple_coroutine(a):
    print('-> start')

    b = yield a
    print('-> recived', a, b)

    c = yield a + b
    print('-> recived', a, b, c)

# runc
sc = simple_coroutine(5)

aa = next(sc)
print(aa)
bb = sc.send(6) # 5, 6
print(bb)
cc = sc.send(7) # 5, 6, 7
print(cc)


-> start
5
-> recived 5 6
11
-> recived 5 6 7



---------------------------------------------------------------------------

StopIteration                             Traceback (most recent call last)

<ipython-input-27-5d216832e9fc> in <module>()
     16 bb = sc.send(6) # 5, 6
     17 print(bb)
---> 18 cc = sc.send(7) # 5, 6, 7
     19 print(cc)


StopIteration: 
class DemoException(Exception):
    """
    custom exception
    """
    pass

def handle_exception():
    print('-> start')

    while True:
        try:
            x = yield
        except DemoException:
            print('-> run demo exception')
        else:
            print('-> recived x:', x)

    raise RuntimeError('this line should never run')

he = handle_exception()
next(he)
he.send(10) # recived x: 10
he.send(20) # recived x: 20

he.throw(DemoException) # run demo exception

he.send(40) # recived x: 40
he.close()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值