手机
当前位置:查字典教程网 >脚本专栏 >python >Python高级应用实例对比:高效计算大文件中的最长行的长度
Python高级应用实例对比:高效计算大文件中的最长行的长度
摘要:前2种方法主要用到了列表解析,性能稍差,而最后一种使用的时候生成器表达式,相比列表解析,更省内存列表解析和生成器表达式很相似:列表解析[ex...

前2种方法主要用到了列表解析,性能稍差,而最后一种使用的时候生成器表达式,相比列表解析,更省内存

列表解析和生成器表达式很相似:

列表解析

[expr for 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() for line in f.readlines()]

f.close()

for line in allLines:

linelen = len(line)

if linelen>longest:

longest = linelen

方法2:简洁

复制代码 代码如下:

f = open(FILE_PATH,"r")

allLineLens = [len(line.strip()) for line in f]

longest = max(allLineLens)

f.close()

缺点:一行一行的迭代f的时候,列表解析需要将文件的所有行读取到内存中,然后生成列表

方法3:最简洁,最节省内存

复制代码 代码如下:

f = open(FILE_PATH,"r")

longest = max(len(line) for line in f)

f.close()

或者

复制代码 代码如下:

print max(len(line.strip()) for line in open(FILE_PATH))

【Python高级应用实例对比:高效计算大文件中的最长行的长度】相关文章:

Python linecache.getline()读取文件中特定一行的脚本

Python中使用动态变量名的方法

python益智游戏计算汉诺塔问题示例

python计算程序开始到程序结束的运行时间和程序运行的CPU时间

Python实现端口复用实例代码

python网络编程学习笔记(一)

Python编写检测数据库SA用户的方法

Python open读写文件实现脚本

使用go和python递归删除.ds store文件的方法

python切换hosts文件代码示例

精品推荐
分类导航