[Python]使用生成器来简化代码

原本只是大概知道生成器是什么,但一直不知道怎么用,或是什么情景下用,后来才发现:

  • 在需要一边读数据一边处理任务时,如果直接为每个任务都写一个函数,那么读数据的部分就要在每个函数都重复一遍

    • 直接将所有任务都写在一起不现实,尤其是当任务比较多时,一旦有时候忘记注释某个任务,可能会影响之后的任务
  • 之后突然想到 yield 这个python关键字,可以将读数据的部分抽出来,写作一个生成器,在任务函数的部分只需用for循环逐个访问即可

简要理解:

yield : 返回一个值,并且记住这个返回的位置,下次迭代就从这个位置后(下一行)开始。

不同于return,一旦return则意味着函数已经执行完毕,而yield则只是暂时停在这里,之后当再次调用这个函数时会返回下一个迭代值。

下面给出用生成器的例子

#An example for using generator

'''
Not using generator, just repeating the file reading operation at every function.
'''
#write an extra 'hello' at each line in file 'f_source', then save it to file 'f_target'
def write_extra(f_source):
    f_target = 'target.txt'
    with open(f_source, 'r') as source, open(f_target, 'w') as target:
        for line in source.readlines():
            target.write(line+'hello'+'\n')
    
#parse each line in file 'f_source'
#the simplest way is just print it out..
def parse_line(f_source):
    with open(f_source, 'r') as source:
        for line in source.readlines():
            line = line.strip().split()   
            print(line)  #print line as a list split by char ' '
        

'''
Using generator
'''        

def read_file(f_source):
    with open(f_source, 'r') as source:
        for line in source.readlines():
            yield line    
       
def new_parse_line(f_source):
    for line in read_file(f_source):
        line = line.strip().split()
        print(line)
        
def new_write_extra(f_source):
    f_target = 'target.txt'
    with open(f_target, 'w') as target:
        for line in read_file(f_source):
            target.write(line+'hello'+'\n')
            

猜你喜欢

转载自www.cnblogs.com/notesbyY/p/11667750.html