• 生成器相关的面试题


     1 def demo():
     2     for i in range(4):
     3         yield i
     4 
     5 g=demo()
     6 
     7 g1=(i for i in g)
     8 g2=(i for i in g1)
     9 
    10 print(list(g1))
    11 print(list(g2))
    1
     1 def add(n,i):
     2     return n+i
     3 
     4 def test():
     5     for i in range(4):
     6         yield i
     7 
     8 g=test()
     9 for n in [1,10]:
    10     g=(add(n,i) for i in g)
    11 
    12 print(list(g))
    2
     1 def add(n,i):
     2     return n+i
     3 
     4 def test():
     5     for i in range(4):
     6         yield i
     7 
     8 g=test()
     9 for n in [1,10]:
    10     g=(add(n,i) for i in g)
    11 
    12 print(list(g))
    13 
    14 复制代码
    15 
    16  
    17 
    18 复制代码
    19 import os
    20 
    21 def init(func):
    22     def wrapper(*args,**kwargs):
    23         g=func(*args,**kwargs)
    24         next(g)
    25         return g
    26     return wrapper
    27 
    28 @init
    29 def list_files(target):
    30     while 1:
    31         dir_to_search=yield
    32         for top_dir,dir,files in os.walk(dir_to_search):
    33             for file in files:
    34                 target.send(os.path.join(top_dir,file))
    35 @init
    36 def opener(target):
    37     while 1:
    38         file=yield
    39         fn=open(file)
    40         target.send((file,fn))
    41 @init
    42 def cat(target):
    43     while 1:
    44         file,fn=yield
    45         for line in fn:
    46             target.send((file,line))
    47 
    48 @init
    49 def grep(pattern,target):
    50     while 1:
    51         file,line=yield
    52         if pattern in line:
    53             target.send(file)
    54 @init
    55 def printer():
    56     while 1:
    57         file=yield
    58         if file:
    59             print(file)
    60 
    61 g=list_files(opener(cat(grep('python',printer()))))
    62 
    63 g.send('/test1')
    64 
    65 协程应用:grep -rl /dir
    3
  • 相关阅读:
    windows权限维持之注册表
    mstsc痕迹清理
    内网常用爆破手法
    RDP攻击&防御
    Java SPI 机制
    mysqldump 数据库备份
    Redis分布式锁
    Seata分布式事务中间件学习和实践
    pytube
    idea github登录
  • 原文地址:https://www.cnblogs.com/haiyan123/p/7280310.html
Copyright © 2020-2023  润新知