Python高级应用实例对比:高效计算大文件中的最长行的长度
时间:2021-11-26 05:36:35
前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,计算
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python绘制直线的方法
2022-10-08 20:01:52
![](https://img.aspxhome.com/file/2023/5/93565_0s.jpg)
对Python3之进程池与回调函数的实例详解
2022-07-30 13:07:01
准备SQL Server 2008透明数据加密
2009-01-22 14:18:00
一文深入了解Python中的继承知识点
2023-01-16 19:57:16
![](https://img.aspxhome.com/file/2023/7/91947_0s.png)
Python ArcPy批量掩膜、重采样大量遥感影像的操作
2023-12-23 14:48:55
![](https://img.aspxhome.com/file/2023/1/81801_0s.png)
python利用opencv实现SIFT特征提取与匹配
2021-07-22 19:08:46
![](https://img.aspxhome.com/file/2023/8/69058_0s.jpg)
python实现简单的井字棋游戏(gui界面)
2023-03-06 23:16:01
![](https://img.aspxhome.com/file/2023/3/83973_0s.png)
Python3实现获取图片文字里中文的方法分析
2023-09-19 09:31:34
php通过pecl方式安装扩展的实例讲解
2023-07-23 07:06:12
详解Python如何巧妙实现数学阶乘n!
2023-07-06 10:22:56
![](https://img.aspxhome.com/file/2023/6/59466_0s.png)
Python实现把回车符\\r\\n转换成\\n
2022-09-21 07:22:14
使用python验证代理ip是否可用的实现方法
2021-03-22 05:30:16
在ASP.NET 2.0中操作数据之十二:在GridView控件中使用TemplateField
2023-07-07 07:02:50
![](https://img.aspxhome.com/file/2023/9/75539_0s.png)
python清理子进程机制剖析
2021-08-10 22:05:19
![](https://img.aspxhome.com/file/2023/8/86618_0s.png)
Java与Python之间使用jython工具类实现数据交互
2023-10-06 18:44:09
网站制作流程及界面交互设计
2007-10-26 12:00:00
![](https://img.aspxhome.com/file/UploadPic/200710/26/2007102612842449s.jpg)
为Python的Tornado框架配置使用Jinja2模板引擎的方法
2022-07-19 03:49:07
Python通过文本和图片生成词云图
2023-08-03 09:39:35
![](https://img.aspxhome.com/file/2023/3/82963_0s.jpg)
关于分页查询和性能问题
2008-03-11 12:25:00
MySQL 通过索引优化含ORDER BY的语句
2010-03-25 10:28:00