生成器

来源:互联网 发布:js实现图片旋转 编辑:程序博客网 时间:2024/04/28 18:08
#1.  判断数据类型是否为可迭代数据类型
In [25]: from collections import  Iterable

In [26]: isinstance('hello',Iterable)
Out[26]: True

In [27]: isinstance([1,2,3],Iterable)
Out[27]: True

In [28]: isinstance(1,Iterable)
Out[28]: False

In [29]: isinstance({1,2,3},Iterable)
Out[29]: True

In [30]: isinstance({"name":"fentiao"},Iterable)
Out[30]: True

In [31]: isinstance((1,2,3),Iterable)
Out[31]: True
#2. 枚举方法,显示为索引-元素对
shopinfo = [
    ('Iphone',1000),
    ('book',200),
    ('fentiao',3500)
]
for i,v in enumerate(shopinfo):
    print i,v
#3.  在for循环里面引用两个变量
shopinfo = [
    ('Iphone',1000),
    ('book',200),
    ('fentiao',3500)
]

for k,v in shopinfo:
    print k,v
    # 4.生成器generator
#   1). 列表生成式受到内存的限制,列表容量是有限的;
#   2). 列表生成式如果只需要前几个元素,浪费内存空间。

 3). 访问生成式:
#         - for循环
#         - g.next()方法
l = [i for i in range(1000)]        # 列表生成式
g = (i for i in range(1000))        # 生成器
g.next()
for i in g:
    print i
    
# 4. 手动实现生成器
#定义一函数fib,实现斐波那契数列(Fibonicci):
# 1, 1, 2, 3, 5, 8, 13, 21..........
#
# def fib(n):
#
# 执行:fib(3)       输出:1,1,2
# 执行:fib(4)       输出:1,1,2,3

def fib(max):
    n,a,b = 0,0,1
    while n < max:
        yield b
        a, b = b, a+b
        n += 1
for i in fib(4):
    print i


def hello():

   print 'a'

    yield  1
    print 'b'
    yield  2
    print 'c'
    yield  3

a = hello()
a.next()
a.next()
a.next()    
    
'''
# 通过yield实现单线程的并发运算
# 异步I/O模型epoll          http   nginx  tomcat

import time
def consumer(name):
    print '%s 准备吃粉条了!' % (name)
    while True:
        fentiao = yield
        print ('粉条[%s]做出来了,被[%s]吃了') % (fentiao, name)
# g = consumer('肖遥')
# g.next()
# g.send('孜然味')

def producer(name):
    c1 = consumer('肖遥')
    c2 = consumer('韩窑')
    c1.next()
    c2.next()
    print '开始制作粉条晚餐了........'
    for i in ['清蒸','油炸','爆炒']:
        time.sleep(1)
        print '[%s] 做了两份粉条,两个人一块吃' %(name)
        c1.send(i)
        c2.send(i)
producer('杨佳晨')

原创粉丝点击