美文网首页
python cookbook 1

python cookbook 1

作者: 二十岁的弹簧 | 来源:发表于2018-12-08 09:18 被阅读0次

创建数据处理管道

  • 指定上层目录,递归地获取下级所有文件和目录,可以用于判断文件类型和文件名,使用到了os.walk和fnmatch

    import os
    import fnmatch
    class Solution:
        def gen_find(filepat, top):
            '''
            filepat: 要匹配的模式
            top: 顶层目录的绝对路径
            '''
            for path, dirlist, filelist in os.walk(top):
                for name in fnmatch.filter(filelist, filepat):
                    yield os.path.join(path, name)
    
  • 展开嵌套的序列,使用yield from语句的递归生成器来解决问题

    from collections import Iterable
    
    def flatten(items, ignore_types=(str, bytes)):
        for x in items:
            if isinstance(x, Iterable) and not isinstance(x, ignore_types):
                yield from flatten(x)
            else:
                yield x
                
    '''
    语句yield from 在你想在生成器中调用其他生成器作为子例程的时候非常有用。
    如果不使用它的话,就必须写额外的for循环
    '''
    def flatten_(items, ignore_types=(str, bytes)):
        for x in items:
            if isinstance(x, Iterable) and not isinstance(x, ignore_types):
                for i in flatten(x):
                    yield i
            else:
                yield x
    

相关文章

网友评论

      本文标题:python cookbook 1

      本文链接:https://www.haomeiwen.com/subject/xdyfhqtx.html