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

yipeiwu_com6年前Python基础

前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脚本暂停执行的几种方法(小结)

1.time.sleep(secs) 参考文档原文: Suspend execution for the given number of seconds. The argument m...

python操作excel的方法

摘要: Openpyxl是一个常用的python库,用于对Excel的常用格式及其模板进行数据读写等操作。 简介与安装openpyxl库 Openpyxl is a Python lib...

Python 删除连续出现的指定字符的实例

源起 我本想删写一小段代码用于删除一串字符串中的连续重复的指定字符,可能也是长时间不写代码,而且有的时候写代码只途快,很多基础知识都忘光了。我用Python写时一切都没有问题,就差一点,...

简单了解Django模板的使用

简单了解Django模板的使用

模板标签include的使用 {%include"police/module/carousel.html"withimgs=imgsdiv_id='#carousel-index'%}...

python基于Selenium的web自动化框架

python基于Selenium的web自动化框架

1 什么是selenium Selenium 是一个基于浏览器的自动化工具,它提供了一种跨平台、跨浏览器的端到端的web自动化解决方案。Selenium主要包括三部分:Selenium...