Python 使用 generator 节省记忆体和组合相似的操作

2018-07-25 11:48 更新

串接不同的操作

def read_line(filename):
    return (line.decode('utf8').rstrip('\n') for line in open(filename))

def filter_comment(lines):
    return (line for line in lines if not line.startswith('#'))

def filter_empty(lines):
    return (line for line in lines if line)

def some_process(filename):
    for line in filter_empty(read_line(filename)):
        ...

def another_process(filename):
    for line in filter_comment(filter_empty(read_line(filename))):
        ...

将多层回圈缩成一层回圈

def read_files(filenames):
    for name in filenames:
        for line in open(name):
            yield line.decode('utf8').rstrip('\n')

def grep(pattern, filenames):
    for line in read_files(filenames):
        if re.match(pattern, line):
            print line

def cat(filenames):
    for line in read_files(filenames):
        print line

若需要走访整个目录下所有档案,可以使用 os.walk。


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号