Python Full Stack road Day21

Source: Internet
Author: User
Tags iterable

first edited October 27, 2017, Friday

Summary
I. Last Class review
Two. iterators
Three. Generator
Four. The co-process function
Homework
Summary today

Summary

References: Alex

    1. Iterators
    2. Generator
    3. Co-process function
I. Last Class review
    1. Decorative Device
      1. Non-parametric adorner
      2. With reference decorator
    2. The adorner prints the original function information
import timefrom functools import wraps        #注意这个def timmer(func):    @wraps(func)        #还有这个    def wrapper():        start_time = time.time()        func()        stop_time = time.time()        print(‘run time is %s ‘ % (stop_time - start_time))    return wrapper@timmer        #index=timmer(index)def index():    ‘come from index‘    print(‘welcome to oldboy‘)index()        #wrapper()print(index.__doc__)        #.__doc__打印函数描述信息,具体不是很了解
Two. iterators
    1. An iterative
      • As long as the object itself has a __iter__ method, it is an iterative
    2. Iterators
      • i = A.iter() #i is an iterator
      • Value can be obtained by __next__
b = {‘a‘:1,‘b‘:2,‘c‘:3}i = iter(b)while True:    print(next(i))#注意:此方法会while会无限循环,报错异常 StopIteration
    1. Exception snapping
b = {‘a‘:1,‘b‘:2,‘c‘:3}i = iter(b)while True:    try:        #注意此行        print(next(i))    except StopIteration:        #and this        break    # and this
    1. For loop mechanism
for key in d:    #d即为d.__iter__() 迭代器放入原位置    print(key)    #并且for循环具有异常捕捉的功能
    1. For loop Implementation iterator
b = {‘a‘:1,‘b‘:2,‘c‘:3}for i in b:    print(i)
    1. Why use iterators
      • Advantages
        1. Iterators provide a way to not rely on an index, so that you can iterate over objects that are not indexed (dictionaries, collections, files)
        2. Iterators are lazy calculations compared to lists, and more memory (Iterators have only one value at the same time in memory)
      • Disadvantages
        1. Unable to get the length of the iterator, using a value that is less flexible than the list index
        2. One-time, can only be taken back to the value, can not be inverted value
    2. Viewing an Iterator object with an iterator
from collections import Iterable,Iterators = ‘hello‘l = [1,2,3]t = (1,2,3)d = {‘a‘:1}set1 = (1,2,3,4)f = open(‘a.txt‘)s.__iter__()l.__iter__()t.__iter__()d.__iter__()set1.__iter__()f.__iter__()                                                    #Iterable 为可迭代的print(isinstance(s,Iterable))        #isinstance()  函数来判断一个对象是否是一个已知的类型,类似 type()。print(isinstance(l,Iterable))print(isinstance(t,Iterable))print(isinstance(d,Iterable))print(isinstance(set1,Iterable))print(isinstance(f,Iterable))
    1. See if it is an iterator
print(isinstance(s,Iterator))        #Iterator 为迭代器print(isinstance(l,Iterator))print(isinstance(t,Iterator))print(isinstance(d,Iterator))print(isinstance(set1,Iterator))print(isinstance(f,Iterator))
Three. Generator
    1. Definition: A generator is a function in which the package contains the keyword yield, which can turn the function into a sequence, returning multiple values
    2. What is the difference between a generator and return
      • Return can return only once to the end of the function, and yield returns multiple values
    3. What did the yield really do?
      • Yield turns the function into a generator (the generator is actually an iterator) (yield will encapsulate __next__ and __iter__ inside the function)
      • Returns can only be returned once with return, and yield returns multiple times
      • The state of the function while pausing and continuing the next run is saved by yield
def test():    print(‘one‘)    yield 1    print(‘two‘)    yield 2    print(‘three‘)    yield 3g = test()        #无输出,此时g为生成器,即把函数变成一个迭代器print(g)        #<generator object test at 0x00000000027E91A8>res = next(g)    #one        next触发生成器的执行print(res)        #1
    1. Yield specific application
def countdown(n):    print(‘start countdown‘)    while n >0:        yield n        n -= 1    print(‘done‘)g= countdown(5)print(next(g))        #start countdown    5print(next(g))        #4print(next(g))        #3print(next(g))        #2print(next(g))        #1print(next(g))        #done    #会报错#for循环写法for i in g:    print(i)#while循环写法while True:    try:        print(next(g))    except    StopIteration:        break
    1. Builder app
#惰性计算def func():    n = 0    while True:        yield n        n += 1f = func()print(next(f))
    1. The most basic implementation of the tail command
import timedef tail(file_path):    with open(file_path,‘r‘) as f:        f.seek(0,2)                    #光标移到最后        while True:                line = f.readline()            #读这一行                if not line:                        time.sleep(0.5)                        continue                else:                        print line,        #print 输出光标不换行tail(‘/tmp/a.txt‘)
    1. The tail command is implemented by the generator (Python2)
import timedef tail(file_path):    with open(file_path,‘r‘) as f:        f.seek(0,2)                    #光标移到最后        while True:                line = f.readline()            #读这一行                if not line:                        time.sleep(0.5)                        print ‘=======‘                        continue                else:                        yield lineg = tail(‘/tmp/a.txt‘)        #函数变成一个生成器for line in g:        print line,
    1. grep commands are implemented by the generator (Python2)
import timedef tail(file_path):    with open(file_path,‘r‘) as f:        f.seek(0,2)                    #光标移到最后        while True:                line = f.readline()            #读这一行                if not line:                        time.sleep(0.5)                        continue                else:                        yield lineg = tail(‘/tmp/a.txt‘)for line in g:        if ‘error‘ in line:                print line,
    1. The grep command is implemented by the generator and has a flow concept
import timedef tail(file_path):    with open(file_path,‘r‘) as f:        f.seek(0,2)                    #光标移到最后        while True:                line = f.readline()            #读这一行                if not line:                        time.sleep(0.5)                        continue                else:                        yield linedef grep(pattern,lines):                #pattern 为grep所抓取的 lines为输入源        for line in lines:                if pattern in line:                        print line,g = tail(‘/tmp/a.txt‘)grep(‘error‘,g)
    1. Tail, grep command final version
import time#定义阶段:定义两个生成器函数def tail(file_path):    with open(file_path,‘r‘) as f:        f.seek(0,2)                    #光标移到最后        while True:                line = f.readline()            #读这一行                if not line:                        time.sleep(0.5)                        continue                else:                        yield linedef grep(pattern,lines):                #pattern 为grep所抓取的 lines为输入源        for line in lines:                if pattern in line:                        yield line#调用阶段:得到俩生成器对象g1 = tail(‘/tmp/a.txt‘)g2 = grep(‘error‘,g1)#使用阶段:next触发执行g2生成器函数for i in g2:        print i,
Four. The co-process function
    1. Eat steamed buns
def eater(name):    print(‘%s start to eat food ‘% name)    food_list = []    while True:        food = yield food_list        print(‘%s get %s, to start eat ‘% (name, food))        food_list.append(food)    print(‘Done‘)e = eater(‘钢蛋‘)print(next(e))print(e.send(‘包子‘))print(e.send(‘韭菜包子‘))    #send 等同于next 有返回值,但是会把后面的参数传给当前行的yieldprint(e.send(‘馅饼‘))
Homework
    1. No
Summary today
    1. Ready to be sorted

Python Full Stack road Day21

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.