codecamp

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

串接不同的操作

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。


Python 使用 iterator 少用 index 增加程式的可读性
Python 少用 else 让程式逻辑更清楚
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }