生成器

生产者消费者模式

import time
def consumer(name):
    print("%s 准备吃包子啦!" %name)
    while True:
       baozi = yield
       print("包子[%s]来了,被[%s]吃了!" %(baozi,name))

def producer(name):
    c = consumer('A')
    c2 = consumer('B')
    c.__next__()
    c2.__next__()
    print("老子开始准备做包子啦!")
    for i in range(10):
        time.sleep(1)
        print("做了2个包子!")
        c.send(i)
        c2.send(i)

producer("alex")
def logger(filename,channel='file'):
    """
    日志方法
    :param filename: log filename 
    :param channel:  输出的目的地,屏幕(terminal),文件(file),屏幕+文件(both)
    :return: 
    """
    print('start logger')
    while True:
        msg = yield
        print("msg",msg)


l = logger('a')

l.__next__()
l.send('hi')
l.send('hi2')

输出: 
start logger
msg hi
msg hi2

生成器, list,islice 可以直接作用在迭代器上

def index_words_iter(text):
    if text:
        yield 0
    for index,letter in enumerate(text):
        if letter == ' ':
            yield index + 1
address = "Four score and seven years ago. .."
a = index_words_iter(address)
print(a,type(a),next(a))
result = list(index_words_iter(address))
from itertools import islice
print(result)
it = index_words_iter(address)
results = islice(it,0,3)
print(list(results))
输出:

[0, 5, 11]
<generator object index_words_iter at 0x0000000009FAD8E0> <class 'generator'> 0
[0, 5, 11, 15, 21, 27, 32]
[0, 5, 11]

生成器读取文件

def index_file(handle):
    offset = 0
    for line in handle:
        if line:
            yield offset
        for letter in line:
            offset +=1
            if letter == '':
                yield offset
# 运行这个生成器函数,也能产生和原来相同的效果。
with open('/tmp/address.txt','r') as f:
it = index_file(f)
results = islice(it,0,3)
print(list(results))

# 输出: [0,5,11]
posted @ 2021-04-22 09:03  ty1539  阅读(44)  评论(0编辑  收藏  举报