17-列表生成器

列表生成式
[x for x in range(10)]
结果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
 
>>> [x*2 for x in range(10)]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
>>>
 
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>
 
def f(n):
    return n**3
 
a=[f(x) for x in range(10)]
 
一种赋值形式
>>> t=(1,2)                        
>>> a,b=t
>>> a
1
>>> b
2
 
t里面的元素多了少了都会报错 必须对应起来
>>> t=(1,2,3)
>>> a,b=t
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 2)
 
列表生成器:  () [  ]  括号的区别  生成器就是一个可迭代对象(iterable) 与垃圾回收机制有关
 >>> s=(x*2 for x in range(10))
>>> s
<generator object <genexpr> at 0x000001C10F76C200>
调用生成器内部方法 来第一个值 s.__next__()
>>> s.__next__()   next(s)  两者等价  在python 时使用 s.next()
0
 
>>> s.__next__()
0
>>> next(s)
2
>>> next(s)
4
当next到最后时 假如没有元素了 会报错误 使用for循环不会报错因为内部存在处理
for i in s:
    print(i)
 
生成器有两种创建方式:1.小括号方式(上面这种) 2.通过已有关键字生成生成器对象
python中有一个非常有用的语法叫做生成器,所利用到的关键字就是yield。有效利用生成器这个工具可以有效地节约系统资源,避免不必要的内存占用。
def foo():          foo()就是一个生成器对象了
    print('ok')
    yield 1
 
for后面加的时可迭代对象  生成器 迭代器字典 列表 都是可迭代对象(内部有__iter__()方法的对象)
斐波那契数列:
使用生成器
def fib(max):
    n,before,after=0,0,1
    while n<max:
        yield before
        before,after=after,before+after
        n=n+1
不使用生成器
def fib(max):
    n,before,after=0,0,1
    while n<max:
        print(before)
        before,after=after,before+after
        n=n+1
 
send() 函数 第一次send前面如果没有next 只能传入一个send(None) 
需要先找到count的位置 才能使用send()传值到count()
def bar():
    print(''ok1)
    count=yield 1
    print(count)
    
   yield 2
 
b=bar()
next(b)
ret=b.send('eeeee')   ret返回的是2  若不清楚流程 断点调试  可以清楚的看到执行流程
 
使用生成器实现伪并发:
 
import time
def  consumer(name):
    print("%s 准备吃包子啦!" %name)
    while True:
        baozi=yield
        print("包子[%s]来了,被[%s]吃了!" %(baozi,name))
 
def Cook(name):
    c = consumer('A')
    c2 = consumer('B')
    c.__next__()
    c2.__next__()
    print("%s开始准备做包子啦!"%name)
    for i in range(10):
        time.sleep(1)
        print("做了2个包子!")
        c.send(i)
        c2.send(i)
 
Cook("xxx")
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/zhwforever/p/10707349.html