在操作某个很多进程都要频繁用到的大文件的时候,应该尽早释放文件资源(f.close())
前2种方法主要用到了列表解析,性能稍差,而最后一种使用的时候生成器表达式,相比列表解析,更省内存
列表解析和生成器表达式很相似:
列表解析
[exPRfor iter_var in iterable if cond_expr]
生成器表达式
(expr for iter_var in iterable if cond_expr)
方法1:最原始longest =0
f= open(FILE_PATH,"r")
allLines= [line.strip()forlineinf.readlines()]
f.close()forlineinallLines:
linelen=len(line)iflinelen>longest:
longest= linelen
方法2:简洁f = open(FILE_PATH,"r")
allLineLens= [len(line.strip())forlineinf]
longest=max(allLineLens)
f.close()
缺点:一行一行的迭代f的时候,列表解析需要将文件的所有行读取到内存中,然后生成列表
方法3:最简洁,最节省内存f = open(FILE_PATH,"r")
longest= max(len(line)forlineinf)
f.close()
或者
printmax(len(line.strip())forlineinopen(FILE_PATH))
参考资料:Python核心编程(第8章)原文地址:曾是土木人转载请注明出处:http://www.cnblogs.com/hongfei/p/3768207.html